What's the right way to pass form element state to sibling/parent elements?

后端 未结 10 759
情话喂你
情话喂你 2020-11-29 15:04
  • Suppose I have a React class P, which renders two child classes, C1 and C2.
  • C1 contains an input field. I\'ll refer to this input field as Foo.
  • M
10条回答
  •  情歌与酒
    2020-11-29 15:12

    With React >= 16.3 you can use ref and forwardRef, to gain access to child's DOM from its parent. Don't use old way of refs anymore.
    Here is the example using your case :

    import React, { Component } from 'react';
    
    export default class P extends React.Component {
       constructor (props) {
          super(props)
          this.state = {data: 'test' }
          this.onUpdate = this.onUpdate.bind(this)
          this.ref = React.createRef();
       }
    
       onUpdate(data) {
          this.setState({data : this.ref.current.value}) 
       }
    
       render () {
          return (
            
    ) } } const C1 = React.forwardRef((props, ref) => (
    )); class C2 extends React.Component { render () { return
    C2 reacts : {this.props.data}
    } }

    See Refs and ForwardRef for detailed info about refs and forwardRef.

提交回复
热议问题