react 之props傳值


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')
)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM