繁体   English   中英

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

[英]ReactJs: How to add/append a component on click of button

<componentX \\>当点击“创建框”按钮时,componentX应该附加在box-container内部。 如果我单击创建框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; 

尝试这样的事情:

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;

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


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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM