ReactJs:如何通过单击按钮添加/附加组件

jam*_*mal 3 javascript reactjs react-component

<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;
Run Code Online (Sandbox Code Playgroud)

小智 7

尝试这样的事情:

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;
Run Code Online (Sandbox Code Playgroud)