【问题标题】:In REACT.js how can I pass a state from child component up to Parent component as a prop在 REACT.js 中,如何将状态从子组件传递到父组件作为道具
【发布时间】:2020-10-30 03:23:34
【问题描述】:

我试图将无类子组件的状态作为道具传递给父类组件。 每次从子组件的下拉“菜单”中选择新区域时,如何在父状态下更新“区域”?

父组件:

进口:

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>
  );
}

【问题讨论】:

标签: javascript reactjs react-hooks react-props react-component


【解决方案1】:

将函数作为 prop 传递给子组件,然后 onchange 调用具有新值的 prop 函数。

// 示例回调函数

  handleOnChange(value) {
     console.log(value);
  }

// 将此函数作为道具传递给孩子

<Menu handleOnChange={this.handleOnChange} />

【讨论】:

    【解决方案2】:

    你可以使用像 redux 和 mobx 这样的状态管理来将状态传递给另一个组件

    【讨论】:

      猜你喜欢
      • 2017-05-18
      • 2020-07-30
      • 2021-11-25
      • 2019-06-19
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      相关资源
      最近更新 更多