【问题标题】:How to insert one component to another component onclick in reactjs?如何在reactjs中将一个组件插入另一个组件onclick?
【发布时间】:2016-01-14 19:39:34
【问题描述】:

在这里,我有两个组件。一个是 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 实现这一点?

【问题讨论】:

  • 这个怎么样 .. 在 component2 上添加一个属性作为 "c1Hidden" 最初设置为 true 。在按钮上添加一个 onClick 事件和一个在单击按钮时将 chHidden 更改为 false 的方法。在
  • @Sathya,我的回答有帮助吗?如果有,请接受。

标签: javascript html css reactjs


【解决方案1】:

将 ComponentTwo 更改为此。

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

【讨论】:

  • 你为什么要让view = &lt;div /&gt; view = null 不够,或者干脆不定义?
  • 我有使用 div/span 初始化视图的习惯,因为在某些情况下我会在渲染方法中返回“视图”,而返回 null 会导致错误。不过这里不需要。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-04
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多