react的组件通信
1、父组件传子组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| import React, {Component} from 'react' class Father extends Component{ render() { return ( <div> <Child msg="我是父组件中的数据:father-data"/> </div> ) } } class Child extends Component{ constructor(props) { super(props) this.state = { message: props.msg } } render() { return ( <div> <div>父组件传过来的数据是:{this.state.message}</div> </div> ) } } export default Father
|
父组件在调用的子组件上定义一个属性msg,属性的值就是需要传递的数据。在子组件中,通过props.msg获取数据。
2、子组件传父组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| import React, { Component } from 'react' class Child extends Component { constructor(props) { super(props) } input = (e) => { console.log(e.target.value); if (e.keyCode == 13) { this.props.send(e.target.value) } } render() { return ( <div> <input type="text" placeholder='please input' onKeyUp={this.input} /> </div> ) } } class Father extends Component { state = { inputVal: "123" } getData = (val) => { this.setState({ inputVal: val }) } render() { return ( <div> <Child send={this.getData} /> 子元素传过来的值:{this.state.inputVal} </div> ) } } export default Father
|
子组件传父组件是通过在子组件中使用props调用父组件中定义的方法(函数)并将自己的数据传递过去。
如上所示,父组件在调用的子组件上定义了send方法用于获取子组件传过来的数据,子组件中调用父组件中的send方法将input的值传过去。
注意:若定义的函数不是箭头函数,则需要在调用的地方使用bind绑定当前this。如this.getdata.bind(this)
3、兄弟组件通信
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| import React, {Component} from 'react' class A extends Component{ state = { inputVal: "module A default value" } handleChange = (e) => { this.setState ({ inputVal: e.target.value }) } sendData = () = { const { sendFn } = this.props sendFn(this.state.inputVal) } render() { return ( <div> <input type="text" value={this.state.inputVal} onChange={this.handleChange}/> <button onClick={this.sendData}>send</button> </div> ) } } class B extends Component{ const { sendVal } = this.props render() { return ( <div> <p>B组件接收到的值是:{sendVal}</p> </div> ) } } class Public extends Component{ state = { inputVal: "module Public default value" } handleUpdate= (inputVal) => { this.setState({ inputVal: inputVal }) } render() { return ( <div> <A sendFn={this.handleUpdate}></A> <B sendValue={this.state.inputVal}></B> </div> ) } } export default Public
|
兄弟组件传值(A传B)需要使用公共组件(Public)进行过渡,即A传Public、Public传B。
A组件通过监听input框输入的值,然后点击按钮,在按钮事件中会调用公共组件中的更新视图(handleUpdate)的方法,将文本框的值作为参数传进去,然后公共组件就获取到A组件的值,然后将公共组件的值传给B组件,B组件再去就接收就能获取到公共组件的值,这样,也就获取到A组件传过来的值。