问题
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