1、父组件传值给子组件vue
父组件向下传值是使用了props属性,在父组件定义的子组件上定义传给子组件的名字和值,而后在子组件经过this.props.xxx调用就能够了。react
2、子组件传值给父组件函数
子组件向父组件传值和vue同样也是利用props和回调函数实现的。this
一、在子组件spa
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传来的函数,在父组件调用这个函数就能够了,通常像下面这样写:code
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;
若是是非父子组件传值,我通常是使用全局定义的状态存储机制来实现的component