react中子组件给父组件传值

组件间通信:

  •  React中,数据是从上向下流动的,也就是一个父组件可以把它的 state/props通过props传递给它的子组件,但是子组件,不能修改props,如果组件需要修改父组件中的数据,则可以通过回调的方法来完成,
  •   说白了就是子组件想要修改父组件的值,就是在父组件调用子组件的地方,传递一个方法,改方法首先在父组件中定义,子组件通过props的获取到父组件传递的方法,子组件就可以调用该方法,也可以利用这个回调传值

定义父组件app.js

  在父组件中定义一个方法传递给子组件

import React, { Component } from "react";

import Home from "./components/Home.jsx";class App extends Component {
  constructor() {
    super();
    this.state = {
      value: "父组件的值",
    };
  }
  render() {
    return (
      <div>
        {this.state.value}     
        <Home changevalue={this.changevalue}></Home>
      </div>
    );
  }
  changevalue = (value) => {
    console.log(value);
    this.setState({
      value,
    });
  };
}

export default App;

定义子组件child

  子组件中从props里获取到父组件传递过来的方法,调用即可,使用的使用一定要注意this问题,这里涉及到给父组件传值(回调里),实际开发中比这要难...,大致思路就是这样

import React, { Component } from "react";

export default class home extends Component {
  constructor(props) {
    super(props);this.state = {
      text: "子组件要传给父组件的值",
    };
  }
  render() {
    
    return (
      <div>
        <button onClick={this.toparent}>点击给父组件</button>
      </div>
    );
  }
  toparent = () => {
    const { changevalue } = this.props;     
    changevalue(this.state.text)        //调用父组件的方法传值
  }
}
原文地址:https://www.cnblogs.com/shun1015/p/13587327.html