React:在不使用 this.props.children 的情况下将组件作为道具传递
React: Pass component as prop without using this.props.children
我有这个组件 Foo.js
:
// 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>
)
}
我想在 <Button>
中渲染 <IconStar>
,我该怎么做?
我不能将它作为 this.prop.children
传递,因为它有更多关于图标道具的逻辑,但在这种情况下我只展示一个演示。
谢谢
您唯一错过的是,要将 JSX 转换为 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>
)
}
如果您使用 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>
所以 ...props 会将 myProps 传递给 IconStar。显然你可以通过任何你想通过的东西。
我有这个组件 Foo.js
:
// 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>
)
}
我想在 <Button>
中渲染 <IconStar>
,我该怎么做?
我不能将它作为 this.prop.children
传递,因为它有更多关于图标道具的逻辑,但在这种情况下我只展示一个演示。
谢谢
您唯一错过的是,要将 JSX 转换为 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>
)
}
如果您使用 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>
所以 ...props 会将 myProps 传递给 IconStar。显然你可以通过任何你想通过的东西。