【问题标题】:ReactJs: How to add/append a component on click of buttonReactJs:如何在单击按钮时添加/附加组件
【发布时间】:2019-02-13 16:36:56
【问题描述】:
说<componentX \> 当点击“创建盒子”按钮时,componentX 应该附加在盒子容器内。如果我单击创建框 3 次,则三个 componentX 应该附加在框容器内(这不是简单地保留组件然后在单击创建框时隐藏和显示)。在 ReactJS 中实现这一点的所有方法是什么。
import ComponentX from './ComponentX.jsx';
class App extends React.Component{
constructor(){
super();
this.state = {
}
}
render(){
let board = Box;
return(
<div>
<a onClick={}>Create Box</a>
<div className="box-container"></div>
</div>
);
}
}
export default App;
【问题讨论】:
标签:
javascript
reactjs
react-component
【解决方案1】:
试试这样的:
import ComponentX from './ComponentX.jsx';
class App extends React.Component{
constructor(){
super();
this.state = {
children: [];
}
}
appendChild(){
this.setState({
children: [
...children,
<componentX \>
]
});
}
render(){
let board = Box;
return(
<div>
<a onClick={() => this.appendChild()}>Create Box</a>
<div className="box-container">
{this.state.children.map(child => child)}
</div>
</div>
);
}
}
export default App;
【解决方案2】:
你可以像这样使用组件状态有条件地渲染:
import ComponentX from './ComponentX.jsx';
class App extends React.Component{
constructor(){
super();
this.state = {
showComp = false;
}
}
handleClick = () => {
this.setState({
showComp: true,
})
}
render(){
let board = Box;
const { showComp } = this.state;
return(
<div>
<a onClick={this.handleClick}>Create Box</a>
<div className="box-container">
{showComp && <ComponentX />
</div>
</div>
);
}
}
export default App;