S
S
sdgroup142019-05-27 13:45:40
React
sdgroup14, 2019-05-27 13:45:40

How to listen event from parent to child components React Typescript?

Hello. Basically the crux of the matter. There is a root component in which I addEventListener('keypress') of the "Escape" button, in the root component there are 4 components in 3 of which I have to forward isMenu = !isMenu(this keypress), i.e. Changes are checked in 3 components and not in 1. I didn’t fully understand redux, I tried to solve it using native methods - it didn’t work out, or the stars didn’t become so that it doesn’t fit into my head :). Through native methods, I tried setState in root and in componentwillreceiveprops child methods. But for some reason all 4 components are updated. I have been working on Angular 2+ for over a year. There, I'm used to either creating new Subject() or through and in the child @Input() private value: boolean
, as I understand it, there is no such thing here?) Please tell me. Preferably with examples
https://codesandbox.io/s/awesome-sea-soyqe

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-05-27
@sdgroup14

1. Update not a property, but the state of a component.
Component State
2. Pass state-based properties to child components:

render() {
  const { value } = this.state;
  return (
    <>
      <Child1 value={value} />
      <Child2 value={value} />
      <Child3 />
    </>
  );
}

3. In child components, you can react to property updates:
componentDidUpdate(prevProps) {
  if (prevProps.value !== this.props.value) {
    this.doSomething();
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question