2017-02-28 46 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。显然,你可以通过任何你想要的东西。