react子組件向父組件傳值


子組件向父組件傳值,注意父組件傳遞函數的時候必須綁定this到當前父組件(handleEmail={this.handleEmail.bind(this)}),不然會報錯

/***實現在輸入框輸入郵箱時,在div中即時顯示輸入內容***/


<body>
    <div id="test"></div>
</body>

//子組件
var Child = React.createClass({
    render: function(){
        return (
            <div>
                郵箱:<input onChange={this.props.handleEmail}/>
            </div>
        )
    }
});

//父組件
var Parent = React.createClass({
    getInitialState: function(){
        return {
            email: ''
        }
    },
    handleEmail: function(event){
        this.setState({email: event.target.value});
    },
    render: function(){
        return (
            <div>
                <div>郵箱:{this.state.email}</div>
                <Child name="email" handleEmail={this.handleEmail.bind(this)}/>
            </div>
        )
    }
});
React.render(
  <Parent />,
  document.getElementById('test')
);

 


免責聲明!

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



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