一 子組件向父組件傳值
//子組件
var Child = React.createClass({
render: function(){
return (
<div>
請輸入郵箱:<input onChange={this.props.handleEmail}/>
</div>
)
}
});
//父組件,此處通過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}/>
</div>
)
}
});
React.render(
<Parent />,
document.getElementById('test')
);
2 常用
//子組件,handleVal函數處理用戶輸入的字符,再傳給父組件的handelEmail函數
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>
請輸入郵箱:<input ref="emailDom" onChange={this.handleVal}/>
</div>
)
}
});
//父組件,通過handleEmail接受到的參數,即子組件的值
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}/>
</div>
)
}
});
React.render(
<Parent />,
document.getElementById('test')
);
二 父組件向子組件傳值
State 和 Props
以下實例演示了如何在應用中組合使用 state 和 props 。我們可以在父組件中設置 state, 並通過在子組件上使用 props 將其傳遞到子組件上。在 render 函數中, 我們設置 name 和 site 來獲取父組件傳遞過來的數據。
var WebSite = React.createClass({ getInitialState: function() { return { name: "菜鳥教程", site: "http://www.runoob.com" }; }, render: function() { return ( <div> <Name name={this.state.name} /> <Link site={this.state.site} /> </div> ); } }); var Name = React.createClass({ render: function() { return ( <h1>{this.props.name}</h1> ); } }); var Link = React.createClass({ render: function() { return ( <a href={this.props.site}> {this.props.site} </a> ); } }); React.render( <WebSite />, document.getElementById('example') );
