父组件向子组件传值

父组件向一级子组件传递值,可以给子组件通过props传递。自上而下进行传递。

  1. import React from 'react';
  2. //定义一个父组件
  3. class Parent extends React.Component{
  4. render(){
  5. return(
  6. <div>
  7. <h1></h1>
  8. <Son info={我是父组件}></Son>
  9. </div>
  10. )
  11. }
  12. }
  13. //定义一个子组件
  14. class Son extends React.Component{
  15. render(){
  16. return(
  17. <div>
  18. <h1>{this.props.info}</h1>
  19. </div>
  20. )
  21. }
  22. }

子组件向父组件传值

子组件向父组件通讯,同样需要父组件向子组件传递props,只是父组件传递的不是值,而是传递一个函数,这个函数的作用域为父组件。子组件调用这个函数,将子组件要传递的信息,作为参数,传递到父组件作用域中。父组件作用域中的该函数执行时,就能调用到这个参数了。

  1. class Parent extends Component {
  2. state = {
  3. data: 'data'
  4. }
  5. getChildMessage (newData) {
  6. this.setState({
  7. data: newData
  8. })
  9. }
  10. render() {
  11. return <div>
  12. <Child fn={(data) => this.getChildMessage(data)} />
  13. //或者 <Child fn={this.getChildMessage} />
  14. </div>
  15. }
  16. }
  17. class Child extends Component {
  18. componentDidMount() {
  19. setTimeout(() => {
  20. this.props. getChildMessage('child-data'); // 调用父组件传来的函数,将数据作为参数传过去
  21. }, 1000);
  22. }
  23. render() {...}
  24. }

兄弟组件之间传值

对于没有直接关联的两个组件,ChildA和ChildB之间,他们之间唯一的联系就是,它们有相同的父组件Parent。
如果我们想由A向B通讯,可以先从A向Parent通讯,再由Parent向B通讯。

  1. class Parent extends Component {
  2. state = {
  3. data: 'data'
  4. }
  5. getChildMessage (newData) {
  6. this.setState({
  7. data: newData
  8. })
  9. }
  10. render() {
  11. return <div>
  12. <ChildA fn={(data) => this.getChildMessage(data)} /> {/* 父组件从子组件A获取到值 */}
  13. <ChildB data={this.state.data} /> {/* Parent向子组件B传值 */}
  14. </div>;
  15. }
  16. }
  17. class ChildA extends Component {
  18. componentDidMount() {
  19. setTimeout(() => {
  20. this.props.getChildMessage('child-data'); // 向Parent传值
  21. }, 1000);
  22. }
  23. render() {...}
  24. }
  25. class ChildB extends Component {
  26. render() {
  27. return <p>{this.props.data}</p>; {/* Parent传来的值 */}
  28. }
  29. }