React子组件与父组件传值

时间:2021-10-02 08:19:53

一 子组件向父组件传值

//子组件
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')
);