如何在ReactJS中有条件地加载组件

512*_*009 23 javascript reactjs

这是来自ReactJS的新入门者.无法获得容易掌握的资源促使我再次敲响SO.问题是这个.我有一个React组件,RegisterAccount当点击时会拍摄另一个组件(弹出窗口),允许用户填写注册帐户所需的详细信息.现在,一旦帐户成功注册,我想将注册帐户添加为另一个组件RegisterAccount.如何设置此通信?

//In RegisterAccount
<addAccount/> //pop-up
<accountAdded/> //if account added, then show this component
Run Code Online (Sandbox Code Playgroud)

小智 27

我是React的新手.我也在寻找如何.我看到了这篇文章!它像下面说的那样

render : function()
{
    return (
        <div>
        { true && <AddAccount /> }
        { false && <AccountAdded /> }
        </div>
    );
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*oix 18

如果我正确理解了您的问题,那么您正在尝试更新状态更改时要显示的组件(例如,用户创建帐户),该状态由子组件更改.这是一个显示child - > parent communication的基本示例.

在这种情况下,RegisterAccount组件是根组件.如果它是另一个组件的子节点,它也需要知道hasAccount本例中使用的状态,那么状态可能会更好地存储在链的较高位置(并作为支柱向下传递).

这个例子的jsfiddle

/** @jsx React.DOM */

var AddAccount = React.createClass({
  handleRegistration: function() {
    this.props.updateAccount(true);
  },
  render: function() {
    return <a onClick={this.handleRegistration}>Create my account</a>;
  }
});

var AccountAdded = React.createClass({
  render: function() {
    return <span>Account exists now</span>;
  }
});

var RegisterAccount = React.createClass({
  getInitialState: function() {
    return {
      hasAccount: false
    };
  },
  updateAccountStatus: function(status) {
    this.setState({
      hasAccount: status
    });
  },
  render: function() {
    return (
      <div>
        {this.state.hasAccount ? <AccountAdded /> : <AddAccount updateAccount={this.updateAccountStatus} />}
      </div>
    );
  }
});

React.renderComponent(<RegisterAccount />, document.body);
Run Code Online (Sandbox Code Playgroud)