Javascript 将子元素添加到React元素
如何将子级添加到React组件Javascript 将子元素添加到React元素,javascript,reactjs,Javascript,Reactjs,如何将子级添加到React组件this.props.children似乎是只读的,因此无法直接对其进行变异 假设我有 var myComponent = <MyComponent someProp="foo"><h1>heading</h1><h2>another heading</h2></MyComponent> var myComponent=标题另一标题 我想添加一些文本作为第三个孩子 我想做到这一点: var
this.props.children
似乎是只读的,因此无法直接对其进行变异
假设我有
var myComponent = <MyComponent someProp="foo"><h1>heading</h1><h2>another heading</h2></MyComponent>
var myComponent=标题另一标题
我想添加一些文本作为第三个孩子
我想做到这一点:
var newChild = <p>some text</p>
myComponent.props.children.add(newChild)
var newChild=一些文本
myComponent.props.children.add(newChild)
所以结果是
<MyComponent someProp="foo"><h1>heading</h1><h2>another heading</h2><p>some text</p></MyComponent>
标题另一标题一些文本
(很明显,add函数不存在,但问题是如何取而代之)保持一个包含所有子组件的状态 尝试添加到状态而不是道具 并在渲染中写入
render() {
return ({<div>this.state.children.map((child) => {return <child as jsx>;}}</div>);
render(){
return({this.state.children.map((child)=>{return;}}});
子类
道具代表插入JSX元素标记之间的内容(请参阅),不应直接修改。事实上,尝试对此.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>)
}
//父组件的呈现方法
render(){
常量元素=…;//构建元素数组
返回(
标题
另一标题
{elements}
)
}
然后,类型为MyComponent
的根元素将知道如何使用这些子元素进行适当的渲染,这些子元素在this.props.children
中提供。如果此组件需要主动触发包含文本,则可以将文本更改回调作为MyComponent
的一个属性,或者只使用组件状态(因此根本不使用该段的子项).您不应该从组件外部修改组件渲染的内容。您应该只更改父组件渲染函数中的子级,或者让MyComponent渲染子级基于道具,例如,您希望何时添加第三个元素?感谢您的输入,我将不得不研究您需要的不同解决方案提供。我想澄清一下我的问题。我实际上想做的是这样的:结果例如:
@J.Doe尽管我仍然不确定你打算做什么,但我刚刚根据你的最后评论更新了我的问题。