簡體   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