props 可以把数据从父传给子,如果想要实现子传给父数据,可以把数据当成函数的参数传递给父组件,下面给一行代码揣摩:

class ParentCom extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            childData:null
        }
    }
    render(){
        return (
            <div>
                <h1>子元素传递过来的数据:{this.state.childData}</h1>
                <ChildCom setChildData={this.setChildData}/>
            </div>
        )
    }
    setChildData = (data) => {
        this.setState({
            childData:data
        })
    }
}

class ChildCom extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            msg: "helloworld"
        }
    }
    render(){
        return (
            <div>
                <button onClick={this.sendData}>传递helloword给父元素</button>
            </div>
        )
    }
    sendData = () => {
        this.props.setChildData(this.state.msg)
    }
}

ReactDOM.render(
    <ParentCom/>,
    document.getElementById('root')
)

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-04
  • 2021-11-12
  • 2021-07-19
  • 2022-12-23
猜你喜欢
  • 2021-05-01
  • 2021-07-05
  • 2022-01-27
  • 2021-12-08
  • 2021-12-13
  • 2021-10-28
  • 2021-05-14
相关资源
相似解决方案