如何使用React.js将两个组件与中间的html /组件链接起来

时间:2016-03-01 17:29:45

标签: reactjs

作为一般性问题,我如何分离两个连接的组件?例如,如果我有一个布局:

section 1
     some list (component 1)

assorted html elements

other components

etc...

section 2
     output from list clicking (component 2)

在这种情况下,我是否在组件1中包含其他html /组件?或者有没有办法让列表和输出显示在页面的不同部分?

1 个答案:

答案 0 :(得分:2)

您可以将第三个父组件作为内部两个组件周围的容器。组件1具有作为回调函数的属性,并且当触发click事件时,组件1调用该回调以及第二组件所需的数据。然后,父组件可以将此数据作为props传递。例如:

function Component1(props) {
  var onClick = function(e) {
    props.callback(e, "hello");
  };
  return (
    <ul>
      <li onClick={onClick}>Some content</li>
    </ul>
  );
}

function Component2(props) {
  return (
    <p>{props.text}</p>
  );
}

var parentComponent = React.createClass({
  onComponent1Click: function(e, val) {
    this.setState({ text: val });
  },
  render: function() {
    return (
      <div>
        <section>
          <Component1 callback={this.onComponent1Click} />
        </section>
        <p>Some other HTML</p>
        <section>
          <Component2 text={this.state.text} />
        </section>
      </div>
    );
  }
});
相关问题