簡體   English   中英

如何將 state 變量的值從一個組件傳遞到另一個組件?

[英]How to pass value of state variable from one component to another?

我有下面的 Form.js 組件,它從輸入表單中獲取數據並進行 API 調用。 響應存儲在我的 walletAssets state 變量中。 現在,如果我想創建一個單獨的組件,比如 Display.js 來顯示存儲在 walletAssets 中的響應,我如何將 walletAssets 的值傳遞給另一個組件,以便在那里使用它?

export default function Form() {
  const [walletAddress, setWalletAddress] = React.useState("");
  const [walletAssets, setWalletAssets] = React.useState([]);

  function handleSubmit(event) {
    request("https://sampleapi.com", query).then((data) =>
      setWalletAssets(data)
    );
  }

  return (
    <div className="form" onSubmit={handleSubmit}>
      <form>
        <input
          type="text"
          className="walletAddress"
          placeholder="Enter your wallet address"
          name="walletAddress"
          onChange={handleChange}
        />
        <button>Submit</button>
      </form>
    </div>
  );
}



export default function Display() {
     //I want to reference the value of walletAssets here
    return()
}

您應該使用反應上下文或 state 管理器,例如 redux

您可以像這樣更改您的顯示組件

export default function Display({walletAssets}) {
    return(
       <>
       {
          walletAssets.map((el) => {
              <p>{el}</p>
          });
       }
       </>
    )
}

並傳遞數據,在表單文件中執行類似的操作

    <div className="form" onSubmit={handleSubmit}>
      <form>
        <input
          type="text"
          className="walletAddress"
          placeholder="Enter your wallet address"
          name="walletAddress"
          onChange={handleChange}
        />
        <button>Submit</button>
      </form>
      <Display walletAssets={walletAssets}/>
    </div>

所以有多種解決方案。
最簡單的方法是將 prop 傳遞給子組件。
像這樣:

export default function Form() {
  const [walletAddress, setWalletAddress] = React.useState("");
  const [walletAssets, setWalletAssets] = React.useState([]);

  function handleSubmit(event) {
    request("https://sampleapi.com", query).then((data) =>
      setWalletAssets(data)
    );
  }

  return (
    <div className="form" onSubmit={handleSubmit}>
      <form>
        <input
          type="text"
          className="walletAddress"
          placeholder="Enter your wallet address"
          name="walletAddress"
          onChange={handleChange}
        />
        <button>Submit</button>
      </form>
    </div>
  );
}



export default function Display(props) {
     //I want to reference the value of walletAssets here
    return(<h1>{props.<property>} )
}

如果要將 object 傳遞給多個組件。 您可以使用一些 state 管理器選項,例如反應上下文或 redux 或 mobx。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM