简体   繁体   中英

React: pass DOM element properties to child

I have a component that looks as follows:

export default class WebGLCanvas extends Component {
  render() {
    return (
      <div class="canvas-container">
        <Renderer></Renderer>
      </div>
    )
  }
}

However, in order to instance the <Renderer> component, I need to provide it a width and a height property, which will only be defined after the .canvas-container is instanced.

What is the appropriate way to pass DOM element properties to child components?

I guess you are trying to implement a Renderer which will need height and width to calculate the dimensions for its child events:

constructor() {
  super();
  this.state = {height: 0, width: 0};
}

componentDidMount() {
  window.addEventListener('resize', this.resetDimensions);
  this.resetDimensions();
}

componentWillUnmount() {
  window.removeEventListener('resize', this.resetDimensions);
}

resetDimensions() {
  var canvasContainer = this.refs.canvasContainer;
  this.setState({width: canvasContainer.clientWidth, height: canvasContainer.clientHeight});
}

The above code basically, sets a height and width as state to your WebGLCanvas component.

Using this you can pass the height and width to the Renderer component as props, like:

return (
    <div className="canvas-container" ref="canvasContainer">
      <Renderer height={this.state.height} width={this.state.width}></Renderer>
    </div>
)

I hope this helps.

PS The call to getDOMNode may or may not be required, depending on the React version.

I think you need to make the canvas-container its own component that passes the needed properties to its children component <Renderer/> . Something like:

Given code:

export default class WebGLCanvas extends Component {
  render() {
    return <CanvasContainer />; // use the canvas-container component
  }
}

Canvas container:

export default class CanvasContainer extends Component {

  constructor(props) {
    super(props);

    // initialize the state
    this.state = {
      width: 0,
      height: 0
    };
  }

  render() {
    const { width, height } = this.state;
    return <Renderer width={width} height={height}></Renderer>
  }
}

And wherever you set width and height in CanvasContainer , you set them through the state:

this.setState({ width, height });

which will re-render the Renderer component and pass these into its props

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