Passing UseState from child component to parent component?

﹥>﹥吖頭↗ 提交于 2021-01-27 20:28:52

问题


I am trying to pass up the state "region" defined in my useState Hook to the parent element. Im not sure where to put the word region in order to do that though?

This is the Child Element

import React from 'react';

export default function SimpleMenu() {

  const [region, setRegion] = useState("Africa");

  const filterRegion = (e) => {
    setRegion(e.target.value);
  };  

  return (
    <div>
      <Button aria-controls="simple-menu" aria-haspopup="true" onClick={handleClick}>
        Filter by Region
      </Button>
      <Menu>
        <MenuItem onClick={ filterRegion } >Africa</MenuItem>
        <MenuItem onClick={ filterRegion }>America</MenuItem>
        <MenuItem onClick={ filterRegion }>Asia</MenuItem>
        <MenuItem onClick={ filterRegion }>Europe</MenuItem>
        <MenuItem onClick={ filterRegion }>Oceania</MenuItem>
      </Menu>
    </div>
  );
}

This is the parent element:

state = {
  countries: [],
  renderedCountries: "Africa",
  selectedCountries: null
}
  
<div id="search_dropdown">
   <Menu countries = renderedCountries = {this.state.renderedCountries}/>
</div>

回答1:


Passing UseState from child component to parent component?

No you shouldn't. This is an anti-pattern of React's Data Flows Down.

If you want both the parent and child component make use of region state, you should lift state up instead.

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      region: 'Africa' // region is owned by Parent component
    }
  }

  // class field syntax
  updateRegion = (region) => {
    this.setState({ region });
  }

  render() {
     // Pass region state down as prop
     // Also provide an updater function for setting region in child component
     return (
       <div id="search_dropdown">
         <Menu updateRegion={this.updateRegion} region={this.state.region} />
       </div>
     );
  }
}


来源:https://stackoverflow.com/questions/64601616/passing-usestate-from-child-component-to-parent-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!