将状态从子组件传递到父组件

IT技术 reactjs ecmascript-6 react-props
2021-05-01 09:26:08

是否有任何正确的方法可以访问子组件状态下的属性并从父组件获取其值?

我有一个名为“itemSelection”的组件,我在其中映射了一个 api 响应以获得一些这样的项目

            <div className="row">
                {this.state.items.map(i => <Item ref="item" id={i.id} name={i.name} quantity={i.quantity} />)}
            </div>

在 Item 组件中,有一个名为“selected”的状态的属性,我想知道它在 itemSelection 组件中是真还是假的值。我知道我可以将props从 itemSelection 传递给 Item 但如果我想要相反的东西怎么办?我可以将数据从 Item 传递到 itemSelection


已编辑

因此,我在父组件“itemSelection”中创建了一个名为“selected”的属性,并将其设置为 =false=(知道我在子组件中也具有相同的属性,该属性也设置为 =false=)

在子组件中,在将 setState 设置为选定的属性以将其更改为 =true= 之后,我将此行放在事件处理程序函数中

this.props.getPropsFromChild(this.state.selected);

然后在父组件中我做了这个功能

getPropsFromChild = (selected) => {
      this.setState({selected: selected}); 
  }

但是还是不行,不知道我设置对了没有。

2个回答

使用 React 中的回调函数将 props 从子组件传递到父组件。或者你也可以使用像 Redux 这样的状态管理库,将数据存储在子组件中,并在父组件中获取数据。

下面的例子说明了如何将 props 从 child 发送到 parent。我在下面分享示例,让您了解如何将props从孩子发送到父母。

ItemSelection:父组件

      //handler function
      getPropsFromChild = (id, name) => {
            console.log(id, name);
       }

       //pass down your handler function to child component as a prop
        <div className="row">
            {this.state.items.map(i => <Item ref="item" id={i.id} name={i.name} getPropsFromChild={this.getPropsFromChild} quantity={i.quantity} />)}
        </div>

项目:子组件

componentDidMount(){
    //access handler function passed to your item component and access it using this.props and send the values as you want to the function
    this.props.getPropsFromChild(“01”, “Hi”);
}

正如评论中试图解释的那样,您可以为此使用回调,但要尽量避免从这样的子组件中获取值。您可以selected在父组件中保持状态。您的Item组件根本不需要为此保持状态。使用来自父级的适当处理程序,您可以轻松更新您的状态。

class App extends React.Component {
  state = {
    items: [
      { id: "1", name: "foo", quantity: 1 },
      { id: "2", name: "bar", quantity: 2  },
      { id: "3", name: "baz", quantity: 3 },
    ],
    selected: "",
  }

  handleSelect = item => this.setState({ selected: item.id })

  render() {
    const { items } = this.state;
    
    return (
      <div>
      Selected item: {this.state.selected}
      {
        items.map( item =>
          <Item key={item.id} item={item} onSelect={this.handleSelect} />
        )
      }
      </div>
    );
  }
}

const Item = props => {
  const { item, onSelect } = props;
  const handleSelect = () => onSelect( item );
  
  return (
    <div style={{border: "1px solid gray"}} onClick={handleSelect}>
      <p><strong>Item id:</strong> {item.id}</p>
      <p><strong>Item name</strong>: {item.name}</p>
      <p><strong>Item quantity</strong>: {item.quantity}</p>
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>