我试图将状态从无类子组件传递为父类组件。 每当在子组件的下拉菜单中选择一个新区域时,如何获得处于“父级”状态的“区域”来更新?
父项:
进口:
import '../Styles/App.css';
import Menu from './Menu';
import { Button } from '@material-ui/core';
import React from 'react';
import CountryList from './CountryList';
父母的状态:
class App extends React.Component {
state = {
countries: [],
region: "Africa",
}
获取API
componentDidMount(){
const apiURL = `https://restcountries.eu/rest/v2/all`;
const response = fetch(apiURL)
.then(resp => resp.json())
.then(data => {
this.setState({
countries: data
});
})
}
渲染APP
render() {
return (
<div className="App">
<section>
<div id="search">
<div id="search_box">
<input type="text" placeholder="Search for a country..."/>
</div>
<div id="search_dropdown">
<Menu />
</div>
</div>
<CountryList countries = {this.state.countries} region = {this.state.region}/>
</section>
</div>
)
}
}
export default App;
子组件:
import React from 'react';
import Button from '@material-ui/core/Button';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
export default function SimpleMenu(props) {
const [region, setRegion] = React.useState("Africa");
return (
<div>
<Button>
Filter by Region
</Button>
<Menu>
<MenuItem> Africa </MenuItem>
<MenuItem> America </MenuItem>
<MenuItem> Asia </MenuItem>
<MenuItem> Europe </MenuItem>
<MenuItem> Oceania </MenuItem>
</Menu>
</div>
);
}
答案 0 :(得分:0)
将函数作为道具传递给子组件,然后onchange用新值调用道具函数。
//示例回调函数
handleOnChange(value) {
console.log(value);
}
//将此功能作为道具传递给孩子
<Menu handleOnChange={this.handleOnChange} />
答案 1 :(得分:0)
您可以使用状态管理(例如redux和mobx)将状态传递给另一个组件