React-组件传值

一、父传子

  1、在 state 中准备要传递给子组件的数据

  2、以属性的方法将值传递给子组件使用的标签位置

  3、在子组件内部使用 this.props 接收父组件传递过来的数据

import React from 'react'

class Father extends React.Component {
  // 1、在 state 中准备要传递给子组件的数据
  state = {
    name: '亚瑟'
  }
  render() {
    return(
      <div>
        {/* 2、以属性的方法将值传递给子组件使用的标签位置 */}
        <Son name={this.state.name} />
      </div>
    )
  }
}

class Son extends React.Component {
  render() {
    return(
      <div>
        {/* 3、在子组件内部使用 this.props 接收父组件传递过来的数据 */}
        父组件传递的值:{this.props.name}
      </div>
    )
  }
}

export default Father

二、子传父

  1、在父组件中声明一个回调函数

  2、将父组件中声明的函数当成 props 属性值传递给子组件

  3、子组件通过 props 调用回调函数

  4、将子组件的数据作为参数传递给回调函数

import React from 'react'

class Father extends React.Component {
  state = {
    parMsg: ''
  }
  // 1. 在父组件中声明一个回调函数 
  parFunc = (msg) => {
    // 4.将子组件的数据作为参数传递给回调函数 
    console.log(msg)
    this.setState({
      parMsg: msg
    })
  }
  render() {
    return(
      <div>
        父组件:{this.state.parMsg}
        {/* 2.将回调函数当成 props 属性值传递给子组件 */}
        <Son getPar={this.parFunc} />
      </div>
    )
  }
}

class Son extends React.Component {
  state = {
    sonMsg: 18
  }
  sonFunc = () => {
    {/* 3.子组件通过 props 调用回调函数 */}
    this.props.getPar(this.state.sonMsg)
  }
  render() {
    return(
      <div>
        子组件:
        <button onClick={this.sonFunc}>点击传值给父组件</button>
      </div>
    )
  }
}

export default Father

三、兄弟传值

  兄弟之间的传值就是:首先 子组件1 向 父组件 传值,然后 父组件 传值给 子组件2

import React from 'react'

/**
 * 完成功能:son1 传值给 son2
 * 传值的过程(子-父-子)
 *  将 子组件1 的值传递给父组件,是子向父传值的方法 也就是回调函数
 *  父组件向 子组件2 发送接收到的 子组件1的值,是父向子传值的方法 也就是 props
 */

class Father extends React.Component {
  // 5.在父组件中定义数据
  state = {
    num: ''
  }

  // 2.父组件开始定义一个回调函数,接收 son1 传递的数据
  getFunc = (msg) => {
    // 6.在回调函数中接收 son1 传递的数据并赋值给 state 中的数据
    this.setState({
      num: msg
    })
  }

  render() {
    return(
      <div>
        <h4>我是父组件</h4>
        <hr/>
        {/* 1.将两个组件全部在父组件中进行使用 */}
        {/* 3.将声明的回调函数当成 props 传递给 son1 组件 */}
        <Son1 getParFunc={this.getFunc} />
        <hr/>
        {/* 7.将 son1 传递过来的数据传递给 son2 */}
        <Son2 num={this.state.num} />
      </div>
    )
  }
}

class Son1 extends React.Component {
  state = {
    son1Num: '20'
  }
  getSonFunc = () =>{
    // 4.在 son1 子组件中调用父组件传值的回调函数,并传值
    this.props.getParFunc(this.state.son1Num)
  }
  render () {
    return (
      <div>
        <h4>我是子组件1</h4>
        <button onClick={this.getSonFunc}>点击传递给子组件2</button>
      </div>
    )
  }
}

class Son2 extends React.Component {
  render () {
    return(
      <div>
        <h4>我是子组件2</h4>
        {/* 8.son2 接收 son1 传递过来的数据 */}
        {this.props.num}
      </div>
    )
  }
}

export default Father
原文地址:https://www.cnblogs.com/xiaowzi/p/12355781.html