反应:不使用this.props.children将组件作为prop传递 [英] React: Pass component as prop without using this.props.children
本文介绍了反应:不使用this.props.children将组件作为prop传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个组件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>
,该怎么做?.
I want to render <IconStar>
inside <Button>
, how do I do that?.
我不能将其作为this.prop.children
传递,因为它在图标道具周围具有更多逻辑,但是在这种情况下,我仅显示一个演示.
I can't pass this as this.prop.children
because it has more logic around the icon prop, but in this case I'm showing only a demo.
谢谢
推荐答案
您唯一想念的是,要让JSX转换为JS自定义组件,应以大写字母开头,例如<TheIcon />
,而小写字母表示本机DOM元素,例如<button />
.:
The only thing you have missed is that for JSX to transpile to JS custom components should be named starting with a capital letter, e.g. <TheIcon />
, while lowercase letter signifies native DOM elements, e.g. <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/
这篇关于反应:不使用this.props.children将组件作为prop传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文