2017-02-28 35 views
2

我有這樣的一個組件Foo.js陣營:通成分的道具,而無需使用this.props.children

// a svg component with a star.svg icon 
import { IconStar } from 'react-svg-icons'; 

// call a button with a custom icon 
<Button icon={ IconStar }> Click to trigger </Button> 

,然後button.js我:

render() { 
    const theIcon = this.props.icon; 
    return (
    <button> 
     {this.props children} 
     {icon() /*this works but i can't pass props inside it*/} 
     <theIcon className={ Styles.buttonIcon } /> 
    </button> 
) 
} 

我想渲染<IconStar><Button>,我該怎麼做?

我不能通過這個作爲this.prop.children,因爲它有更多的圖標道具周圍的邏輯,但在這種情況下,我只顯示一個演示。

感謝

回答

3

你已經錯過了唯一的一點是,要JSX到transpile JS自定義組件應該開始一個大寫字母,例如命名<TheIcon />,而小寫字母表示本地DOM元素,例如, <button />

render() { 
    const TheIcon = this.props.icon; // note the capital first letter! 
    return (
    <button> 
     {this.props children} 
     <TheIcon className={ Styles.buttonIcon } /> 
    </button> 
) 
} 

https://jsfiddle.net/03h2swkc/3/

+0

啊!當然,什麼是基本概念。謝謝! –

0

如果您使用ES6那麼你可以使用擴展運算符的屬性傳遞到下面的成分,我認爲這可能會解決你的問題:

var MyIcon = (props) => { 
 
    return <i {...props}> { 
 
    props.className 
 
    } < /i> 
 
}; 
 
var MyButton = (props) => { 
 
    return (<button> { 
 
     props.children 
 
    }<MyIcon {...props} /></
 
    button >); 
 
} 
 

 
ReactDOM.render(< 
 
    MyButton className = 'my-icon'>My Button Text</MyButton> , 
 
    document.getElementById('myComponent') 
 
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 

 
<div id='myComponent'></div>

所以...道具會將myProps傳遞到IconStar。顯然,你可以通過任何你想要的東西。