ReactJs:如何 add/append 单击按钮时的组件
ReactJs: How to add/append a component on click of button
说 <componentX \>
当点击 "create box" 按钮时,componentX 应该附加到 box-container 里面。如果我点击 create box 3 次,那么三个 componentX 应该附加到 box-container 中(这并不是简单地保持组件然后在点击 create box 时隐藏和显示)。在 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;
您可以像这样使用组件状态有条件地渲染:
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;
尝试这样的事情:
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;
说 <componentX \>
当点击 "create box" 按钮时,componentX 应该附加到 box-container 里面。如果我点击 create box 3 次,那么三个 componentX 应该附加到 box-container 中(这并不是简单地保持组件然后在点击 create box 时隐藏和显示)。在 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;
您可以像这样使用组件状态有条件地渲染:
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;
尝试这样的事情:
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;