代码之家  ›  专栏  ›  技术社区  ›  Omotayo Obafemi

使用上下文API重构反应组件代码

  •  0
  • Omotayo Obafemi  · 技术社区  · 2 年前

    我要重构这段代码。任务是避免通过 用户名 , 更新用户名 一直往下走,没有直接通过道具。我想在不使用任何第三方库或框架的情况下做到这一点。 这是代码

    import { useState } from "react";
    
    export default function App() {
      const [username, setUsername] = useState("owais");
      const [otherUsername, setOtherUsername] = useState("calvin");
      return (
        <>
          <User username={username} updateUsername={setUsername} />
          <User username={otherUsername} updateUsername={setOtherUsername} />
        </>
      );
    }
    
    function User({ username, updateUsername }) {
      return (
        <div>
          Username: {username}
          <UsernameEditor username={username} updateUsername={updateUsername} />
        </div>
      );
    }
    
    function UsernameEditor({ username, updateUsername }) {
      return (
        <div>
          <input
            type="text"
            value={username}
            onChange={(e) => updateUsername(e.target.value)}
          />
        </div>
      );
    }
    

    我决定使用ContextAPI,但如果不复制用户组件和userNameEditor组件代码或将道具直接传递给组件,我似乎找不到实现这一点的方法。我有什么办法可以做到这一点? 这就是我目前拥有的

    import { createContext, useContext, useState } from "react"
    
    interface AppContextInterface {
      username: string;
      setUsername: Function;
      otherUsername: string;
      setOtherUsername: Function;
    }
    
    const AppCtx = createContext<AppContextInterface | null>(null);
    
    export default function App() {
      const [username, setUsername] = useState("owais");
      const [otherUsername, setOtherUsername] = useState("calvin");
    
      const value = { username, setUsername, otherUsername, setOtherUsername };
    
      return (
        <AppCtx.Provider value={value}>
          <User />
          <OtherUser />
        </AppCtx.Provider>
      );
    }
    
    function UsernameEditor() {
      const appContext = useContext(AppCtx);
      return (
        <div>
          <input
            type="text"
            value={appContext?.username}
            onChange={(e) => appContext?.setUsername(e.target.value)}
          />
        </div>
      );
    }
    
    function User() {
      const appContext = useContext(AppCtx);
      return (
        <div>
          Username: {appContext?.username}
          <UsernameEditor />
        </div>
      );
    }
    
    function OtherUserEditor() {
      const appContext = useContext(AppCtx);
      return (
        <div>
          <input
            type="text"
            value={appContext?.otherUsername}
            onChange={(e) => appContext?.setOtherUsername(e.target.value)}
          />
        </div>
      );
    }
    
    function OtherUser() {
      const appContext = useContext(AppCtx);
      return (
        <div>
          Username: {appContext?.otherUsername}
          <OtherUserEditor />
        </div>
      );
    }
    
    0 回复  |  直到 2 年前