如何向 React 组件添加子组件。this.props.children
似乎是只读的,所以不能直接改变它。
假设我有
var myComponent = <MyComponent someProp="foo"><h1>heading</h1><h2>another heading</h2></MyComponent>
我想补充一点<p>some text</p>
作为第三个孩子。
我想完成这个:
var newChild = <p>some text</p>
myComponent.props.children.add(newChild)
这样结果就是
<MyComponent someProp="foo"><h1>heading</h1><h2>another heading</h2><p>some text</p></MyComponent>
(显然 add 函数不存在,但问题是该怎么做)
The children
prop 表示插入到 JSX 元素的标签之间的内容(请参阅docs https://facebook.github.io/react/docs/jsx-in-depth.html#children-in-jsx),并且不应该直接修改。事实上,尝试对其中的任何内容进行修改this.props
通常是不可想象的。
为了解决您的特定问题,您似乎希望定义将哪些子项添加到组件中,如下所示:
// parent component's render method
render() {
const elements = ...; //build up an array of elements
return (<MyComponent someProp="foo">
<h1>heading</h1>
<h2>another heading</h2>
{elements}
</MyComponent>)
}
类型的根元素MyComponent
然后就会知道如何使用这些子项进行正确的渲染,这些子项可以在this.props.children
。如果此组件需要主动触发包含文本,那么您可以包含一个文本更改回调作为 propMyComponent
,或者只使用组件状态(从而完全避免使用该段落的子级)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)