将子项添加到React元素

时间:2016-12-07 22:03:09

标签: javascript reactjs

如何将子项添加到React组件。 $(function() { $("btnDisplay").click(function () { displayPopUpWindow(4); }); function displayPopUpWindow(reportType) { //code } }); 似乎是只读的,因此无法直接改变它。

我们说我有

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)

(显然,添加功能不存在,但问题是该做什么)

2 个答案:

答案 0 :(得分:1)

children prop表示在JSX元素的标记之间插入的内容(请参阅docs),不应该直接修改。事实上,尝试对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中可用。如果此组件需要主动触发包含文本,那么您可以将文本更改回调作为MyComponent的支柱包含,或者只使用组件状态(从而完全避免使用该段落的子项)。

答案 1 :(得分:0)

保持一个包含所有子组件的状态

尝试添加状态而不是道具

并在渲染中写

render() {
return ({<div>this.state.children.map((child) => {return <child as jsx>;}}</div>);
相关问题