我是 React 新手,我对一些基本的东西感到困惑。
我需要在 DOM 渲染后,在单击事件上将组件附加到 DOM。
我的初步尝试如下,但没有成功。但这是我想尝试的最好的事情。 (提前为将 jQuery 与 React 混合而道歉。)
ParentComponent = class ParentComponent extends React.Component {
constructor () {
this.addChild = this.addChild.bind(this);
}
addChild (event) {
event.preventDefault();
$("#children-pane").append(<ChildComponent/>);
}
render () {
return (
<div className="card calculator">
<p><a href="#" onClick={this.addChild}>Add Another Child Component</a></p>
<div id="children-pane">
<ChildComponent/>
</div>
</div>
);
}
};
希望我清楚我需要做什么,并且希望您能帮助我找到合适的解决方案。
使用 React 时,不要使用 jQuery 来操作 DOM。 React 组件应该渲染一个表示在特定状态下它们应该是什么样子;翻译成什么 DOM 由 React 本身负责。
您想要做的是将“决定渲染内容的状态”存储在链的更高位置,并将其向下传递。如果你正在渲染n
孩子们,该状态应该由包含您的组件的任何内容“拥有”。例如:
class AppComponent extends React.Component {
state = {
numChildren: 0
}
render () {
const children = [];
for (var i = 0; i < this.state.numChildren; i += 1) {
children.push(<ChildComponent key={i} number={i} />);
};
return (
<ParentComponent addChild={this.onAddChild}>
{children}
</ParentComponent>
);
}
onAddChild = () => {
this.setState({
numChildren: this.state.numChildren + 1
});
}
}
const ParentComponent = props => (
<div className="card calculator">
<p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
<div id="children-pane">
{props.children}
</div>
</div>
);
const ChildComponent = props => <div>{"I am child " + props.number}</div>;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)