简体   繁体   中英

How to link two components with html/components inbetween with React.js

As a general question, how would I separate two connected components? For example, if I had a layout:

section 1
     some list (component 1)

assorted html elements

other components

etc...

section 2
     output from list clicking (component 2)

In this instance, do I include the other html/components within component 1? Or is there a way to have the list and the output appear in different sections of the page?

You could have a 3rd parent component as a container around the inner two components. Have component 1 have a property which is a callback function, and have component 1 call that callback with the data needed by the second component when the click event is fired. The parent component can then pass this data on as props. For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM