您的当前位置:首页正文

ReactNative从零开始笔记5-组件传值(父子组件/兄弟组

来源:华拓网

一、使用环境

  • Mac 电脑 系统10.14.2
  • Xcode9.4
  • react-native-cli版本 2.0.1
  • react-native: 0.57.3
  • webstorm

二、父子组件传值

2.1 父组件传值到子组件(顺传)
  • props 属性传值
  • 通过定义子组件的ref, 通过ref 获取子组件,调用子组件方法传值

2.1.1 通过props 属性传值

  • 通过 <SonComponent gif={'公瑾水战法'}></SonComponent> 其中git 属性传值

  // 子组件
class SonComponent extends Component{
   /**
    * 1.父组件通过属性给子组件传值
    * @type {{gif: *}} 属性申明, 具有提示
    */
   static propTypes ={
            gif: PropTypes.string,
     }
     // 属性默认值
     static defaultProps={
             gif: '没有礼物',
     }
     render(){
          return (
             <View style={styles.sonComponentStyle}>
                   <Text>我是子组件</Text>
                   <Text>父组件传过值是:
                          <Text style={{fontSize: 14, color: 'red'}}>{this.props.gif}      </Text>
                     </Text>
               </View>
               )
           }
      }
   // 父组件
  export default  class FatherComponnent extends Component{
      constructor(props){
         super(props);
       }
     render(){
           return (
                   <View style={styles.fatherStyle}>
                       <Text>我是父组件</Text>
                        <SonComponent gif={'公瑾水战法'}></SonComponent>
                  </View>
                )
            }
    }

2.1.2 通过定义子组件的ref, 通过ref 获取子组件,调用子组件方法传值

  • ref标记子组件<SonComponent ref='son'>
  • 调用子组件方法this.refs.son.changeMessageEvent('给儿子100元');

  // 子组件
class SonComponent extends Component{
 // 初始化状态 
constructor(props){
      super(props);
      this.state={
        msg:''
     }
   }
/**
 * 2.父组件调用该方法 - 改变state值 - 给该组件传值
 * @param inputMsg 父组件传值参数
 */
changeMessageEvent(inputMsg){
    this.setState({
        msg: inputMsg
    })
}

render(){
    return (
        <View style={styles.sonComponentStyle}>
            <Text>我是子组件</Text>
            <Text>{this.state.msg}</Text>
        </View>
    )
  }
}
// 父组件
export default  class FatherComponnent extends Component{
    constructor(props){
        super(props);
     }
    render(){
        return (
        <View style={styles.fatherStyle}>
            <Text>我是父组件</Text>
            <Button title= '方法传值给子组件' color={'red'} onPress={()=>{
                this.refs.son.changeMessageEvent('给儿子100元');
            }}></Button>
            <SonComponent ref='son'></SonComponent>
        </View>
    )
  }
}
2.2 子组件传值到父组件(逆传)
  • 通过在父组件定义方法,子组件props调用进行事件传递值
  • 子组件中callBack是在父组件中定义的回调方法名
  • 父组件引用子组件的时候定义callBack属性方法回调
 <SonComponent callBack={(m)=>{this.changeMoney(m);}}</SonComponent>

// 子组件
class SonComponent extends Component{
  render(){
      return (
          <View style={styles.sonComponentStyle}>
              <Text>我是子组件</Text>
               <Button title={'给父组件100元'} onPress={()=>{
                this.props.callBack(100);
               }}>
              </Button>
        </View>
      )
   }
}
// 父组件
export default  class FatherComponnent extends Component{
   constructor(props){
       super(props);
       this.state= {
        money: 0
      }
    }
  changeMoney(m){
      this.setState({
          money: m
      })
  }
  render(){
       return (
        <View style={styles.fatherStyle}>
            <Text>我是父组件</Text>
            <SonComponent callBack={(m)=>{
               this.changeMoney(m);
            }}></SonComponent>
            <Text>获取到子组件的{this.state.money}元</Text>
        </View>
    )
   }
}

三、无关联组件传值

  • 使用方法: 通知(如果你有其他语言基础,可以理解为KVO)
  • 注意销毁观察者
  • 使用步骤:
    3.1 增加通知观察者, 接收到通知改变值

 // 增加观察者
 componentDidMount(): void {
    this.listener = DeviceEventEmitter.addListener('ggMakeMoney', (m)=>{
        this.setState({
            reciveMoney:m
        })
    })
}
 // 组件销毁的时候移除观察者
componentWillUnmount(): void {
     this.listener.remove();
}

3.2 发送通知传值

DeviceEventEmitter.emit('ggMakeMoney',100);

完成代码实现: 哥哥挣100元,给弟弟花

   //哥哥组件
class GegeComponet extends Component{
  constructor(props){
    super(props);
 }
// 哥哥挣钱,发送通知
  ggMakeMoney(){
    DeviceEventEmitter.emit('ggMakeMoney',100);
  }
  render(){
     return(
        <View>
            <Button title='哥哥挣钱' onPress={()=>{
                this.ggMakeMoney();
            }}></Button>
        </View>
    );
  }
}
//弟弟组件
class DidiComponet extends Component{
   constructor(props){
       super(props);
       this.state={
          reciveMoney: 0
      }
 }
// 增加观察者
componentDidMount(): void {
    this.listener = DeviceEventEmitter.addListener('ggMakeMoney', (m)=>{
        this.setState({
            reciveMoney:m
        })
    })
}
// 组件销毁的时候移除观察者
componentWillUnmount(): void {
    this.listener.remove();
}

render(){
    return(
        <View>
            <Text>弟弟收到哥哥的钱{this.state.reciveMoney}</Text>
        </View>
    );
   }
 }
// 父组件
export default  class FatherComponnent extends Component{
   render(){
       return (
        <View style={styles.fatherStyle}>
            <Text>我是父组件</Text>
            <GegeComponet></GegeComponet>
            <DidiComponet></DidiComponet>
        </View>
    )
   }
 }