这篇文章主要为大家展示了“如何实现React组件之间的通信”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“如何实现React组件之间的通信”这篇文章吧。

谢家集ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联建站的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!
1.定义两个子组件child-1和child-2
//child-1 子组件-1为输入框
class Input extends React.Component{
constructor(...args){
super(...args);
}
render(){
return
}
}
//child-2 子组-2为显示框
class Show extends React.Component{
constructor(...args){
super(...args);
}
render(){
return
}
}2.定义父组件Parent并且将两个子组件插入到父组件中
class Parent extends React.Component{
constructor(...args){
super(...args);
}
render(){
return(
);
}
}现在的任务是在组件1总输入一些文字,同时在组件2中同时显示出来。
分析:要让组件2与组件1同步,就让组件1和2都去绑定父组件的状态。也就是说让两个组件受控。数据的走向是,组件1将自身的数据提升到父层,并且保存在父层的状态中。父层中的数据通过组件2中的props属性传递到组件2中,并在视图层进行绑定。
第一步先绑定
//在父层中的constructor中定义状态为一个空的message,this.state = {message:''}
class Parent extends React.Component{
constructor(...args){
super(...args);
this.state = {
message:''
}然后在父组件中的
接着来我们进入到
class Show extends React.Component{
constructor(...args){
super(...args);
}
render(){
return {this.props.onShow}
}这样组件2显示层的数据已经绑定好了,接下来我们只要改变父亲层状态中的message的内容就可以使绑定的显示层的内容跟着一起变化
将输入层的状态(数据)提升到父亲组件中.下面是改写后的组件1
class Input extends React.Component{
constructor(...args){
super(...args);
}
//将输入的内容更新到自身组件的状态中,并且将改变后的状态作为参数传递给该组件的一个自定义属性onInp()
fn(ev){
this.props.onInp(ev.target.value);
}
render(){
//用onInput(注意react中采用驼峰写法和原生的略有不同)绑定fn()函数
return
}
}看到这里可能会有一个问题:onInp()和content没有啊?不要急,接着看
接着改写父组件中的输入层子组件1,
class Parent extends React.Component{
constructor(...args){
super(...args);
this.state = {
message:''
};
}
//传进的text是其提升上来的状态,然后再更新父组件的状态
fn(text){
this.setState({
message:text
})
}
render(){
return(
/*
onInp就出现在这里,并绑定一个函数,
并且有一个content将父组件的状态同步到子组件中
*/
);
}
}写完的代码是这样的
// 父组
class Parent extends React.Component{
constructor(...args){
super(...args);
this.state = {
message:''
};
}
onInp(text){
this.setState({
message:text
})
}
render(){
return(
);
}
}
//child-1
class Input extends React.Component{
constructor(...args){
super(...args);
}
fn(ev){
this.props.onInp(ev.target.value);
}
render(){
return
}
}
//child-2
class Show extends React.Component{
constructor(...args){
super(...args);
}
render(){
return {this.props.onShow}
}
}
//最后渲染出
ReactDOM.render(
,
document.getElementById('app')
);以上是“如何实现React组件之间的通信”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!
文章标题:如何实现React组件之间的通信
URL地址:http://www.jxjierui.cn/article/joedic.html


咨询
建站咨询
