react组件间的传值方法

一、父子组件间的传值:

Father.jsx文件

import React, { Component} from 'react'
import Son from './Son.jsx'
{/*引入子组件*/}
export default class Father extends Component{

constructor(){

super();
this. state = {
message: 'hello',
sonVal: null
}
}
render(){
return (
< div id= "father" >
< h1 >Father组件 </ h1 >
< button onClick= {() =>{ this. setState({ message: 'world'})} } >
修改
</ button >
{ /* <Son data="test data value"/> */ }
< p >选择了那种水果: {this. state. sonVal } </ p >
< Son data= {this. state. message } handle= {this. testAction. bind( this) } />

{/*子组件中传递参数或者方法*/} 


</ div >
)
}

// 接收子组件数据
testAction( value){
console. log( this);
console. log( value);
this. setState({ sonVal: value});
} }

Son.jsx

import React, { Component} from 'react'

export default class Son extends Component{
constructor(){
super();
this. state = {
select: '苹果'
}
}
render(){
let arr = [ '苹果', '香蕉', '西瓜'];
return (
< div id= "son" >
< h1 >Son组件 </ h1 >
< p >接收到的值为: {this. props. data } </ p >

{
arr. map(( item, index) =>{
return (
< p key= { index } >
{ item }:
< input type= "radio" value= { item }
checked= {this. state. select == item }
onChange= {this. inputChange. bind( this) } />
</ p >
)
})
}
</ div >
)
}

inputChange( ev){
let value = ev. target. value;
this. setState({ select: value});

// 调用父组件的方法,将值传递给父组件
this. props. handle( value);
}
}

 二、非父子组件间的传值

 One.jsx文件

import React, { Component} from 'react'
import PubSub from 'pubsub-js'

export default class One extends Component{
constructor(){
super();
console. log( 'constructor');
this. state = {
message: null
}
}
render(){
console. log( 'render');
return (
< div >
< h1 >One组件 </ h1 >
< p >接收到的值为: {this. state. message } </ p >
</ div >
)
}

// 创建并且渲染完成的方法
componentDidMount(){
console. log( 'componentDidMount');

//监听子组件的事件
this. token = PubSub. subscribe( 'send-data', ( eventName, data) =>{
console. log( 'subscribe执行了');
console. log( data);
this. setState({ message: data});
})

// $on

}
//组件将要销毁
componentWillUnmount(){
console. log( 'componentWillUnmount');
// 组件销毁时,需要移除监听
PubSub. unsubscribe( this. token);

// $off

}
}

Two.jxs

import React, { Component} from 'react'
import PubSub from 'pubsub-js'

export default class Two extends Component{
render(){
return (
< div >
< h1 >Two组件 </ h1 >
< input type= "text" ref= "in" />
< button onClick= {this. sendAction. bind( this) } >发送 </ button >
</ div >
)
}

sendAction(){
// 发送信息给one组件
PubSub. publish( 'send-data', this. refs. in. value);
// $emit
}
}

猜你喜欢

转载自www.cnblogs.com/yunshangwuyou/p/9480441.html
今日推荐