Q
Q
qo_0p2016-03-01 22:19:10
React
qo_0p, 2016-03-01 22:19:10

How to bind two child components in react js?

There are two child components with one parent, how to connect them so that when one child component is activated (for example, pressing a button), the second child component (for example, text) changes?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lemme, 2016-03-01
@qo_0p

class Parent extends Component {

  constructor() {
    super();
    this.state = {
      text: ''
    };
  }

  // Ссылку на этот метод будем передавать в Button компонент.
  buttonClick() {
    this.setState({ text: Date.now() });
  }
  
  render() {
    return (
      <div>
        // Ну, а тут передаем состояние text (родительского компонента) через props в дочерний (Text)
        <Text text={ this.state.text } />
        <Button onClick={ () => this.buttonClick() }/>
      </div>
    );
  }
}

function Button(props) {
  return <button onClick={ props.onClick }>Click me</button>
}

function Text(props) {
  return <span>{ props.text }</span>
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question