React中父子组件间传值

975 阅读2分钟

1. 父组件==>子组件

原理:在父组件中给所需传值的子组件添加某属性,在子组件中使用 this.props.xxx 接收父组件传过来的值。

上代码

  • Parent.jsx
import React, { Component } from 'react';
import Child from './Child.jsx'
class Parent extends Component {
  constructor(props) {
    super(props)

    this.state = {
      content: ''
    }
  }
  render() {
    //解构赋值语法
    const { content } = this.state
    return (
      <div style={{backgroundColor:'tan',height:'100px'}}> 
      <span>我是父组件:</span>
        <input 
          type="text"  
          onChange={(e)=>{
            this.setState({content:e.target.value})
          }}
        />
        {/* 给子组件<Child /> 添加一个自定义属性“message” 并设置其属性值为this.state.content */}
        <Child message={content}/>
      </div>
    );
  }
}

export default Parent;

如上代码已经在父组件中定义好了子组件 并将值传给了子组件 此时要定义一个子组件并且接收父组件传过来的值

  • Child.jsx
import React, { Component } from 'react'

export default class Child extends Component {
  // 首先写好构造函数props 我们从父组件中传下来的值就藏在props之中
  constructor(props) {
    super(props)
    this.state={
    }
  }
  render() {
    return (
      // 从props中取出message。
      <div style={{backgroundColor:"teal",height:'50px',width:'200px'}}>
        接收到的内容:{this.props.message}
      </div>
    )
  }
}

页面的效果:

action1116.gif 子组件接收到了父组件传递的message渲染在了组件内部

2. 子组件==>父组件
原理:利用this.props.xxx接收一个自定义事件 子组件执行事件时利用事件对象获取到传递的值,在父组件中展示

  • Parent1.jsx
import React, { Component } from "react";
import Child1 from "./Child1.jsx";

export default class Parent1 extends Component {
  constructor(props) {
    super(props);

    this.state = {
      content: "",
    };
  }
  render() {
    const { content } = this.state;
    return (
      <div
        style={{
          backgroundColor: "teal",
        }}
      >
        {/* 
          在父组件代码中使用子组件Child1 并且给Child1自定义属性属性值为一个事件
          在子组件执行某事件时 就会自动setState给content。完成子传父
            */}
        <Child1
          getData={(msg) => {
            this.setState({ content: msg });
          }}
        />
        父组件接收到的内容:{content}
      </div>
    );
  }
}

  • Child1.jsx
import React, { Component } from "react";

export default class Child extends Component {
  constructor(props) {
    super(props);

    this.state = {
      testcontent: "",
    };
  }
  render() {
    return (
      <div
        style={{
          width: "300px",
          height: "50px",
          backgroundColor: "tan",
        }}
      >
        子组件要传的内容:
        <input
          type="text"
          name=""
          id=""
          // 此处onChange将input变为受控组件 执行此事件后state里的testcontent将变为input中输入的值onChange={(e) => {
            this.setState({ testcontent: e.target.value });
          }}
        />
        <button
         // 此处点击事件会将执行父组件中传过来的getData方法
          onClick={() => {
            this.props.getData(this.state.testcontent);
          }}
        >
          点击
        </button>
      </div>
    );
  }
}


页面的效果:

action1114.gif

3. 兄弟组件之间的传值
原理:完成兄弟组件之间的传值 两个兄弟组件有共同的父组件 可以视作由一个子组件向父组件传递,再由父组件向另一个子组件传递 即 先子传父再父传子

image.png

  • Parent.jsx
import React, { Component } from 'react'
import Child1 from './Child1.jsx'
import Child2 from './Child2.jsx'
export default class Parent extends Component {
    constructor(props){
        super(props)

        this.state = {
            content:''
        }
    }
  render() {
    //   接收Child1的内容 传送给Child2
   
    return (
      <div style={{backgroundColor:'pink'}}>
          <span>组件1</span>
          <Child1 getData={(msg)=>{
              console.log(msg);
              this.setState({content:msg})
          }}/>
          <span>组件2</span>
          <Child2 message= {this.state.content}/>

      </div>
    )
  }
}

  • Child1.jsx
import React, { Component } from 'react'

export default class Child1 extends Component {
    constructor(props) {
      super(props)
    
      this.state = {
         content:''
      }
    }
  render() {
    return (
        <div style={{backgroundColor:'tan',width:'800px',height:'50px'}}>
           <input type="text" name="" id="" onChange={(e)=>{
                this.setState({content:e.target.value})
            }}
            />
            <button onClick={()=>{
                this.props.getData(this.state.content);
            }}
            >按钮</button>
        </div>
    )
  }
}

  • Child2.jsx
import React, { Component } from "react";

export default class Child2 extends Component {
  constructor(props) {
    super(props);

    this.state = {
      content: this.props.message,
    };
  }
  render() {
    return (
      <div style={{ backgroundColor: "teal", width: "800px", height: "30px" }}>
        <span>接收到的内容是:</span>
        {this.props.message}
      </div>
    );
  }
}

页面的效果:

action1115.gif

词不达意 感谢阅读 Thanks♪(・ω・)ノ