reactjs - 将数据从 child 发送到 parent React

标签 reactjs

我不知道我哪里做错了。我无法将数据从 child 发送到 parent 。 这里有什么问题? 我如何从子状态中获取状态并发送给父状态?

这是子组件

import React from 'react';

export class Child extends React.Component{
  constructor(props) {
    super(props);
    this.state= {
      counter2: 5
    }
  }

  render() {
    return(
      <div>
        <button onClick={this.props.data}>Click me</button><span>{this.state.counter2}</span>
      </div>
    );
  }
}

export default Child;

我想更新父组件中的状态

import React from 'react';
import {Child} from './Child';

export default class Parent extends React.Component{
  constructor(props){
    super(props);
    this.state= {
      counter: 0
    }
  }

  update(){
    this.setState({
      counter: this.props.state.counter2
    });
  }

  render(){
    return(
      <div>
        <span>{this.state.counter}</span>
        <Child data={this.update.bind(this)}/>
      </div>
    );
  }
}

但是我有一个错误: × 类型错误:无法读取未定义的属性“计数器”?

我不明白我做错了什么!

谢谢

最佳答案

实际上,您的父级props 中没有state 属性。 您不能以这种方式获取 child 的状态:

this.props.state.counter2

Props ONLY 从父组件传递给子组件(如果您不使用 Redux 或其他状态管理库)。

不过,你可以这样传递它:

父组件

import React from 'react';
import {Child} from './Child';

export default class Parent extends React.Component{
  constructor(props){
    super(props);
    this.state= {
      counter: 0
    }
  }

  update(value){
    return () => {
       this.setState({
         counter: value
       });
    }
  }

  render(){
    return(
      <div>
        <span>{this.state.counter}</span>
        <Child data={this.update.bind(this)}/>
      </div>
    );
  }
}

子组件

import React from 'react';

export class Child extends React.Component{
  constructor(props) {
    super(props);
    this.state= {
      counter2: 5
    }
  }

  render() {
    return(
      <div>
        <button onClick={this.props.data(this.state.counter2)}>Click me</button><span>{this.state.counter2}</span>
      </div>
    );
  }
}

export default Child;

关于reactjs - 将数据从 child 发送到 parent React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50077235/

相关文章:

javascript - 使用 Redux、React 和 react-router-dom 4.x 时从动态组件获取 ref

javascript - react Material ui自动完成元素焦点onclick

reactjs - React Hooks useCallback 的简单示例出现问题

javascript - 是否可以在 React 项目中使用 dotenv?

javascript - 当我在表单中输入输入时,React 组件不必要地重新渲染

node.js - 如何在特定环境中的开发机器上启动React App?

reactjs - 是否可以在 Next.js 中通过国际化重定向服务器端?

javascript - react 错误index.js :1452 Warning: Each child in an array or iterator should have a unique "key" prop

javascript - 图像未在 reactjs 中加载

reactjs - 使用redux-thunk和直接调用dispatch()有什么区别