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

时间:2019-06-13 08:13:02

标签: reactjs components react-props

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

1 个答案:

答案 0 :(得分:1)

您可以将函数从父对象传递给子对象,该函数可以设置父对象中对象的状态。

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'));

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