首页 > 解决方案 > 在 React JS 中从父组件更改子状态

问题描述

我有一些关于我的问题的文章,我知道如果我想从父组件更改子组件的状态,我必须提升父组件中的状态,但我不想这样做。
我有 2 个组件:

const Parent = () => {
  const changeChild = () => {
  
  }
  
  return (
    <button onClick={changeChild}>change state</button>
    <Children/>
  )
}


const Children = () => {
  const [state, setState] = useState(false); //this state should be changed by parent to TRUE
}

问题:如何使用父组件将状态更改true为位于子组件中的状态?changeChild谁能帮忙?

标签: reactjs

解决方案


您可以尝试另一种方法。使用 useRef、forwardRef 和 useImperativeHandle 检查此代码段。

父.js

import { useRef } from "react";
import { Child } from "./Child";

export default function () {
  const ref = useRef();

  return (
    <div>
      <button onClick={() => ref.current.setState()}>
        Click me to toggle the value in child
      </button>
      <Child ref={ref} />
    </div>
  );
}

Child.js

 import { forwardRef, useState, useImperativeHandle } from "react";

 export const Child = forwardRef(function (props, ref) {
  //this state should be changed by parent to TRUE
  const [state, setState] = useState(false);

  function changeValue() {
    return function () {
      setState(!state);
    };
  }
  useImperativeHandle(ref, () => ({
    setState: () => changeValue()()
  }));

  return (
    <div>
      <b>changed value from parent</b> :{" "}
      {state ? "Parent triggered to true" : "Parent triggered to false"}
    </div>
  );
});

注意:这不是推荐的,尝试使用提升状态。这只是为了理解目的,这是一种反模式

工作代码框


推荐阅读