React子组件向父组件传值

zhuanbike 2022-1-6 762

class Father extends React.Component {
      handleGetMsg = (value) => {
        console.log(value)
        this.setState({
          test: value
        })
      }
      state = {
          
        }
      render() {
        return (
          <div>
            <p>从子组件中接收到得数据: {this.state.test}</p>
            <Child getMsg={this.handleGetMsg}/>//把父元素的函数先传给子元素,让子元素在此函数中修改数据
          </div>
        )
      }
    }
    class Child extends React.Component {
      state = {
        val: 'haha'
      }
      handleClick = () => {
        this.props.getMsg(this.state.val)
      }
      render() {
        return (
          <div>
            <button onClick={this.handleClick}>子组件</button>
          </div>
        )
      }
    }
    ReactDOM.render(<Father />, document.getElementById('root'))



最新回复 (0)
发新帖