如何在react中onclick将一个组件插入到另一个组件中

How to insert one component to another component onclick in reactjs?

本文关键字:组件 一个 插入 另一个 react onclick      更新时间:2023-09-26

这里,我有两个组件。一个是ComponentOne,另一个是ComponentTwo。目前我只渲染一个组件,是ComponentTwo。

var ComponentOne = React.createClass({
    render: function() {
        <div className="card">
            <h2>Component one</h2>
        </div>
    }
});
var ComponentTwo = React.createClass({
    render: function() {
        <div className="card">
            <h2>Component two</h2>
            <button>Insert</button>
        </div>
        <ComponentOne />
    }
});

如果我点击插入按钮,ComponentOne将在componenttwo类元素卡之后插入。如何用reactjs实现这一点?

将ComponentTwo更改为this

var ComponentTwo = React.createClass({
getInitialState: function(){
   return {"insert":false};
},
handleClick : function(){
    this.setState({"insert":true});
},
render: function() {
    var view;
    if(this.state.insert)          {
      view = <ComponentOne />;
    }
    return <div className="card">
        <h2>Component Two</h2>
        <button onClick={this.handleClick} >INsert </button>
        {view}    
    </div>
}
});
相关文章: