V
V
Vlad Tokarev2020-02-14 13:35:49
React
Vlad Tokarev, 2020-02-14 13:35:49

How to execute a child element method in React?

Let's say there is a parent component App, inside of which there are several RandomStringand RefreshButton
When you click on RefreshButtonme from App, you need to send a command to RandomString, so that each such component executes its internal methodRandomString.refresh()

export class App extends Component<{}> {
  constructor(props: {}) {/* ... */}

  protected refreshItems() {
    // Тут надо как-то вызвать метод refresh() у дочерних RandomString
  }

  render(): ReactNode {
    return (
      <div>
        <RandomString />
        <RandomString />
        <RandomString />
        <RefreshButton onClick={this.refreshItems}  />
      </div>
    );
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Alexandrovich, 2020-02-14
@Vadiok

export class App extends Component<{}> {
    this.myRef = React.createRef();
  constructor(props: {}) {/* ... */}

  protected refreshItems() {
    // Тут надо как-то вызвать метод refresh() у дочерних RandomString
  if(this.myRef&&this.myRef.current&&this.myRef.current.refresh){
      this.myRef.current. refresh()
   }
  }

  render(): ReactNode {
    return (
      <div>
        <RandomString     this.myRef = React.createRef(); />
        <RefreshButton onClick={this.refreshItems}  />
      </div>
    );
  }
}

and RandomString needs https://reactjs.org/docs/forwarding-refs.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question