简体   繁体   English

将对象从子对象传递到父状态

[英]Passing object to parent state from child

有什么方法可以将对象从子组件推到父道具?

You can pass a function from the parent to the child that can set the state of an object in the parent. 您可以将函数从父对象传递给子对象,该函数可以设置父对象中对象的状态。

import React, { Component } from 'react';
import { render } from 'react-dom';

const Child = ({saveObj}) => (
  <div
    onClick={() => {
      saveObj({test: "test"})
    }}
  >
    Click to set obj
  </div>
) 

class App extends Component {
  constructor() {
    super();
    this.state = {
      obj : null
    };
  }

  render() {
    return (
      <div>
        Obj is: {JSON.stringify(this.state.obj)}
        <p>
          <Child saveObj={obj => {this.setState({obj})}} />
        </p>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

Live Example: https://stackblitz.com/edit/react-snivhc 实时示例: https//stackblitz.com/edit/react-snivhc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM