如何通过子组件的形式正确更改父母的状态?

时间:2020-05-23 19:52:04

标签: javascript reactjs forms functional-programming state

提交表单后,我试图从子组件更新父组件上共享值的状态:

父母

function App() {
  const [search, setSearch] = useState("default");

  function handleSubmitted(n) {
    setSearch(n);
    console.log(search);                                //Doesn't update, and value lost after refresh
  }

  return (
    <>
      <Switch>
        <Route exact path="/">
          <Landing onSubmit={handleSubmitted} />        //Child responsible to update state
        </Route>
        <Route path="/add">
          <Add />
        </Route>
        <Route path="/menus">
          <RestaurantList search={search} />            //Receives updated state after a redirect
        </Route>
      </Switch>
    </>
  );
}

孩子

export default function Landing(props) {
  return (
    <>
      <section className="center fullpage" id="landing">
        <div className="landing__contents">
          <h1>DineIn</h1>
          <div className="search">
            <form onSubmit={props.onSubmit} >                   //Call function on parent
              <input type="text" placeholder="D Spot Cafe" />
            </form>
          </div>
        </div>
      </section>
    </>
  );
}

我正试图让<RestaurantList />接收用户在<Landing />中键入的搜索值以执行实际的搜索查询功能,但是状态没有改变。

我的结构完全错误吗?

2 个答案:

答案 0 :(得分:0)

由于您的示例还不是完整的示例,因此我尝试为您提供一个示例,通过子组件的形式更改父状态,并且该状态用于该父组件的另一个子组件

父组件

import React, {useEffect, useState} from 'react';
import Child from "./Child";
import Sibling from "../Sibling";

function CParent(props) {

    const [status, setStatus] = useState(false);

    function setOpeningValue(status) {
        console.log('From Child to Parent:' + status);
        setStatus(status);
    }
    return (
        <div>
            <Child setOpeningValue={setOpeningValue}/>
            <Sibling status={status}/>
        </div>
    );
}
export default CParent;

子组件

import React, {useEffect, useState} from 'react';

// Child to Parent communication
function Child(props) {
    const {setOpeningValue} = props;
    const [isOpen, setOpen] = useState(false);

    function clickHandler() {
        setOpen(!isOpen);
        setOpeningValue(`changes is ${!isOpen}`);
    }
    return (
        <div>
            <button onClick={clickHandler}>Open</button>
        </div>
    );
}
export default Child;

同级组件

import React, {useEffect, useState} from 'react';

function Sibling(props) {
    const {status} = props;

    return (
        <div>
            From Child to Parent to Another Child (Sibling) {status}
        </div>
    );
}
export default Sibling;

答案 1 :(得分:0)

<form>元素上的onSubmit事件只有在您将一个提交按钮放入然后按下后才会触发。

如果要在键入文本输入时更改状态,则需要侦听输入文本元素上的onChange事件。因此,您将获得以下内容:

<form>
  <input type="text" placeholder="D Spot Cafe" onChange={props.onChange} value={props.search}>
</form>

请注意,您还需要将搜索值传递给子组件。