admin管理员组

文章数量:1287484

Say <ponentX \> when onClick of "create box" button, the ponentX should append inside of box-container. If i click create box 3 times, then three ponentX should append inside box-container (It's not that simply keeping the ponent then hide and show when click of create box). What are all the ways to achieve this in 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;

Say <ponentX \> when onClick of "create box" button, the ponentX should append inside of box-container. If i click create box 3 times, then three ponentX should append inside box-container (It's not that simply keeping the ponent then hide and show when click of create box). What are all the ways to achieve this in 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;

Share Improve this question edited Sep 8, 2018 at 17:40 jamal asked Sep 8, 2018 at 17:08 jamaljamal 531 gold badge1 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

Try something like this:

import ComponentX from './ComponentX.jsx';

class App extends React.Component{
    constructor(){
        super();

        this.state = {
            children: [];
        }
    }

    appendChild(){
        this.setState({
            children: [
                ...children,
                <ponentX \>
            ]
        });
    }

    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;

You can conditionally render by using ponent state like this:


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;

本文标签: javascriptReactJs How to addappend a component on click of buttonStack Overflow