react 组件之间的传值

组件之间的传值,包括父子组件传值, 兄弟组件之间的传值,其中父子组件包括父组件向子组件传值和子组件向父组件传值,现在一一来介绍一下.

一.父组件向子组件传值
父组件通过state向子组件传值,

// 父组件

constructor(props){

super(props);

this.state = { name : 'yuxi' }}

render(){ return 我是子组件 }

// 子组件

constructor(props){

super(props)

}

render(){

return

{this.props.name}

}

二.子组件向父组件传值
有三种方式实现子组件向父组件传值.

(一)父组件通过state传值给子组件,子组件通过props获取父组件的传递值

//(一)传值,即在父组件中声明好自己的state,然后传值,如下//1.初始值constructor() {

super();

this.state = {

  stateValue:true    }

}//2.如有改变设定值this.setState({

stateValue: false})//3.在父组件中传值

const huoquValue = this.props.stateValue;

if ( !this.props.stateValue ) {

    console.log('stateValue', this,.props.stateValue)

}

}

值得注意一点的是,setState 是一个异步方法,需要render值行的时候才会触发。可以参考博客【 React的setState立即执行方案】。

(二)父组件将方法传给子组件,子组件通过props来获取。

//父组件文件中:

classTestHtmlextendsReact.Component{

//1.方法的声明

propsFunction() {

    console.log('声明在父组件的方法')

}

render() {

    return (

        //2.传递           

    )

}

}functionmapStateToProps(state, ownProps){ return {

}

}functionmapDispatchToProps(dispatch){ return {

    ...bindActionCreators(action, dispatch)

}

}

export default connect(mapStateToProps, mapDispatchToProps)(TestHtml)

//子组件中获取

------ 本文结束 ------