ReactJs:如何在单击按钮时添加/添加组件

时间:2018-09-08 17:08:09

标签: javascript reactjs react-component

说“ <componentX \>”时,单击“创建框”按钮时,componentX应该附加在框容器内部。如果我单击创建框3次,则应在box-container内附加三个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;

2 个答案:

答案 0 :(得分:0)

您可以使用如下组件状态有条件地进行渲染:


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;

答案 1 :(得分:0)

尝试这样的事情:

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;