【问题标题】:Passing object to parent state from child将对象从子状态传递给父状态
【发布时间】:2019-10-27 18:59:07
【问题描述】:

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

【问题讨论】:

标签: reactjs components react-props


【解决方案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

【讨论】:

    猜你喜欢
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 2019-02-17
    • 2020-09-09
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多