react中子組件向父組件傳值

reactjs是一枚新進(jìn)小鮮肉,跟gulp搭配流行一段時(shí)間了。工作或者面試中經(jīng)常遇到這樣的問(wèn)題,“子組件如何向父組件傳值?”。其實(shí)很簡(jiǎn)單,概括起來(lái)就是:react中state改變了,組件才會(huì)update。父寫好state和處理該state的函數(shù),同時(shí)將函數(shù)名通過(guò)props屬性值的形式傳入子,子調(diào)用父的函數(shù),同時(shí)引起state變化。子組件要寫在父組件之前。具體寫法看下面3個(gè)例子。

1. 例子一

這里如下圖,用戶郵箱為父,綠色框?yàn)樽印?父組件為用戶輸入的郵箱設(shè)好state,即“{email: ''}”,同時(shí)寫好處理state的函數(shù),即“handleEmail”,這兩個(gè)名稱隨意起;再將函數(shù)以props的形式傳到子組件,子組件只需在事件發(fā)生時(shí),調(diào)用父組件傳過(guò)來(lái)的函數(shù)即可。


//以下所有例子對(duì)應(yīng)的html
<body>
    <div id="test"></div>
</body>
//子組件
var Child = React.createClass({
    render: function(){
        return (
            <div>
                請(qǐng)輸入郵箱:<input onChange={this.props.handleEmail}/>
            </div>
        )
    }
});
//父組件,此處通過(guò)event.target.value獲取子組件的值
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')
);

2. 例子二

有時(shí)候往往需要對(duì)數(shù)據(jù)做處理,再傳給父組件,比如過(guò)濾或者自動(dòng)補(bǔ)全等等,下面的例子對(duì)用戶輸入的郵箱做簡(jiǎn)單驗(yàn)證,自動(dòng)過(guò)濾非數(shù)字、字母和"@."以外的字符。

Paste_Image.png
//子組件,handleVal函數(shù)處理用戶輸入的字符,再傳給父組件的handelEmail函數(shù)
var Child = React.createClass({
    handleVal: function() {
        var val = this.refs.emailDom.value;
        val = val.replace(/[^0-9|a-z|\@|\.]/ig,"");
        this.props.handleEmail(val);
    },
    render: function(){
        return (
            <div>
                請(qǐng)輸入郵箱:<input ref="emailDom" onChange={this.handleVal}/>
            </div>
        )
    }
});
//父組件,通過(guò)handleEmail接受到的參數(shù),即子組件的值
var Parent = React.createClass({
    getInitialState: function(){
        return {
            email: ''
        }
    },
    handleEmail: function(val){
        this.setState({email: val});
    },
    render: function(){
        return (
            <div>
                <div>用戶郵箱:{this.state.email}</div>
                <Child name="email" handleEmail={this.handleEmail.bind(this)}/>
            </div>
        )
    }
});
React.render(
  <Parent />,
  document.getElementById('test')
);

3. 例子3

如果還存在孫子組件的情況呢?如下圖,黑框?yàn)楦?,綠框?yàn)樽?,紅框?yàn)閷O,要求子孫的數(shù)據(jù)都傳給爺爺。原理一樣的,只是父要將爺爺對(duì)孫子的處理函數(shù)直接傳下去。

Paste_Image.png
//孫子,將下拉選項(xiàng)的值傳給爺爺
var Grandson = React.createClass({
    render: function(){
        return (
            <div>性別:
                <select onChange={this.props.handleSelect}>
                    <option value="男">男</option>
                    <option value="女">女</option>
                </select>
            </div>
        )
    }
});
//子,將用戶輸入的姓名傳給爹  
//對(duì)于孫子的處理函數(shù),父只需用props傳下去即可
var Child = React.createClass({
    render: function(){
        return (
            <div>
                姓名:<input onChange={this.props.handleVal}/>
                <Grandson handleSelect={this.props.handleSelect}/>
            </div>
        )
    }
});
//父組件,準(zhǔn)備了兩個(gè)state,username和sex用來(lái)接收子孫傳過(guò)來(lái)的值,對(duì)應(yīng)兩個(gè)函數(shù)handleVal和handleSelect
var Parent = React.createClass({
    getInitialState: function(){
        return {
            username: '',
            sex: ''
        }
    },
    handleVal: function(event){
        this.setState({username: event.target.value});
    },
    handleSelect: function(event) {
        this.setState({sex: event.target.value});
    },
    render: function(){
        return (
            <div>
                <div>用戶姓名:{this.state.username}</div>
                <div>用戶性別:{this.state.sex}</div>
                <Child handleVal={this.handleVal.bind(this)} handleSelect={this.handleSelect.bind(this)}/>
            </div>
        )
    }
});
React.render(
  <Parent />,
  document.getElementById('test')
);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容