当前位置: 移动技术网 > IT编程>开发语言>JavaScript > react 组件间通信,父子间通信

react 组件间通信,父子间通信

2019年05月08日  | 移动技术网IT编程  | 我要评论

一、父组件传值给子组件

     父组件向下传值是使用了props属性,在父组件定义的子组件上定义传给子组件的名字和值,然后在子组件通过this.props.xxx调用就可以了。

二、子组件传值给父组件

  子组件向父组件传值和vue一样也是利用props和回调函数实现的。

  1、在子组件

  

import react, { component } from 'react';
class datechild extends component {
   constructor(props, context) {
     super(props, context);
     this.state = {
        val:'我是子组件值'
     }
  }
  childclick (e) {
      this.props.callback(this.state.val)
  }
  render() {
     return (
         <div onclick={(e) => this.childclick(e)}>点击传值给父组件</div>
     );
  }

}

export default datechild;

因为是从子组件向父组件传值,所以要在子组件中定义点击事件触发函数,而从父组件传来的函数通过this.props来调用,这点和父组件向下传值是一样的。 然后我们在父组件中定义子组件的props传来的函数,在父组件调用这个函数就可以了,一般像下面这样写:

import react, { component } from 'react';
import datechild from '../component/datechild.js'
class date extends component {
     constructor(props, context) {
        super(props, context);
         this.state = {
             content:'我是父组件值'
         }
     }
     callback (mess) {
         this.setstate({
           content: mess
         })
     }
     render() {
         return (
            <div>{this.state.content}
                 <datechild callback={this.callback.bind(this)} />
       </div>
         );
     }
}
export default date;

如果是非父子组件传值,我一般是使用全局定义的状态存储机制来实现的

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网