【问题标题】:Set state from props change in react functional component?从反应功能组件中的道具更改设置状态?
【发布时间】:2021-05-31 01:58:03
【问题描述】:

我有一个简单的反应功能组件,如下代码所示

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <Test
        children={
          <React.Fragment>
            <label>Name: </label>
            <input type="text" onChange={(e) => setData(e)} /> 
          </React.Fragment>
        }
      />
    </div>
  );
}

export function Test({ children }) {
  const [data, setData] = useState("");
  return (
    <>
      <div>{children && children}</div>
      <div>{data}</div>
    </>
  );
}

我的问题是如何在 onChange 事件触发时更新Test 组件内的data 状态? 这是sandbox

希望任何人都可以帮助我.. 提前致谢

【问题讨论】:

    标签: reactjs react-hooks react-props react-functional-component react-state


    【解决方案1】:

    你不必那样送孩子。 React 有一种特定的方式来处理孩子,这更容易做和维护。在你的情况下,你只需要提升你的状态并将statecallback作为道具发送。

    import React, { useState } from "react";
    import "./styles.css";
    
    export default function App() {
     const [data, setData] = React.useState('')
      return (
        <div className="App">
          <Test data={data}>
             <> // shorthand for ReactFragment
                <label>Name: </label>
                <input type="text" onChange={(e) => setData(e.target.value)} value={data}/> 
             </>
          </Test>
        </div>
      );
    }
    
    export function Test({ data, children }) {
      return (
        <>
          <div>{children && children}</div>
          <div>{data}</div>
        </>
      );
    }
    

    【讨论】:

    • 我不想在父组件中创建另一个状态。谢谢你雷伊
    • 哦,没想到。
    【解决方案2】:

    您可以为此使用render props 技术,如果您不喜欢重大重构,您可以保持您的模式不变。

    工作演示 - https://codesandbox.io/s/flamboyant-monad-hw2lu?file=/src/App.js

    import React, { useState } from "react";
    import "./styles.css";
    
    export function Child(props) {
      const { setData } = props;
      return (
        <React.Fragment>
          <label>Name: </label>
          <input type="text" onChange={(e) => setData(e.target.value)} />
        </React.Fragment>
      );
    }
    
    export default function App() {
      return (
        <div className="App">
          <Test
            render={(props) => {
              const { setData } = props;
              return <Child setData={setData} />;
            }}
          ></Test>
        </div>
      );
    }
    
    export function Test(props) {
      const [data, setData] = useState("");
      const { render } = props;
      return (
        <>
          <div>{render({ setData })}</div>
          <div>{data}</div>
        </>
      );
    }
    
    

    【讨论】:

    • 非常感谢迪瓦卡。这完全是我想要的。
    猜你喜欢
    • 2022-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 2017-09-23
    • 2019-08-13
    • 1970-01-01
    • 2021-06-10
    相关资源
    最近更新 更多