简体   繁体   中英

Calling methods on child components in React

I'm trying to bypass React's render() for some deeper components that are drawing to Canvas, but I still want to use React to pass props, etc. The problem I'm running into is that I can't figure out how to call methods on children like this.

What I have is basically:

<canvasRenderer state="active" mode={42}>
  <itemFoo fill="red" stroke="black" />
  <itemBar fill="blue" stroke="black" />
</canvasRenderer>

Then, within canvasRenderer I want to do:

constructor() {
  requestAnimationFrame(this.drawFrame);
}

drawFrame = () => {
  React.Children.forEach(children, (child) => {
    child.drawFrame(); // does not exist
  });
}

Any suggestions on how to make this work?

If you need to call a method on the DOM element itself, use refs .

class Child extends React.component {

  drawFrame () {
    console.log('look ma, a child method!')
  }

  render () {
    <div ref={ el => this.el = el }>Some child content</div>
  }

}

class Parent extends React.component {
  componentDidMount () {
    requestAnimationFrame(this.drawFrame);
  }

  drawFrame = () => {
    React.Children.forEach((child) => {
      child.el.drawFrame(); // does not exist
    });
  }
}

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