【问题标题】:ReactJs: How to add/append a component on click of buttonReactJs:如何在单击按钮时添加/附加组件
【发布时间】:2019-02-13 16:36:56
【问题描述】:

<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;

【问题讨论】:

    标签: javascript reactjs react-component


    【解决方案1】:

    试试这样的:

    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;
    

    【讨论】:

      【解决方案2】:

      你可以像这样使用组件状态有条件地渲染:


      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;
      

      【讨论】:

        猜你喜欢
        • 2021-06-28
        • 2021-12-09
        • 2022-09-30
        • 1970-01-01
        • 2020-08-21
        • 1970-01-01
        • 2019-08-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多