簡體   English   中英

React:DRY 功能組件集 state 帶變量

[英]React: DRY Functional component set state with variable

我有一系列輸入組件,只想使用一個 onChange function。

在 Class 組件中,我知道我可以執行以下操作以適應不同的狀態:

inputChange(input) {
    this.setState({
      [input.name]: input,
    });
  }

在功能組件中,如何僅使用一個onChange function 更新 state?

組件示例:

function Form(){
  const [selectedClient, updateSelectedClient] = useState(null);
  const [selectedLocation, updateSelectedLocation] = useState(null);
 

  return(

   <input
     value={selectedClient}
     id="selectedClient"
     name="selectedClient"
     onChange={???}
   />
   <input
    value={selectedLocation}
    id="selectedLocation"
    name="selectedLocation"
    onChange={???}
  />
  );
}

Thank you for the time!

由於這是一種形式,我會將狀態合並為一個,用 object 初始化它,然后當調用onChange處理程序時,用該值更新由輸入id標識的屬性。

這里使用useEffect來記錄更新state的結果。

 const { useEffect, useState } = React; function Example() { const [form, setForm] = useState({}); useEffect(() => { console.log(form); }, [form]) function handleChange(e) { // Grab the id and value from the input const { id, value } = e.target; // Create a new object by spreading out the current form // state, and setting the state property to the new value setForm({...form, [id]: value }); } return ( <div> Client: <input value={form.client} id="client" name="client" onChange={handleChange} /> Location: <input value={form.location} id="location" name="location" onChange={handleChange} /> </div> ); } // Render it ReactDOM.render( <Example />, document.getElementById("react") );
 input { display: block; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

使用您在 class 中使用的相同方法,不同之處在於您將客戶端和位置合並為一個 object,它將代表 state,並且您利用了id

 const {useState} = React; function Form(){ const [selectedClientOrLocation,setSelectedClientOrLocation] = useState({ selectedClient:"", selectedLocation:"" }) const handleChange = (e) =>{ setSelectedClientOrLocation({...selectedClientOrLocation,[e.target.id]:e.target.value}) } return( <form> <label htmlFor="selectedClient"> Client <input value={selectedClientOrLocation.selectedClient} id="selectedClient" name="selectedClient" onChange={handleChange} /> </label> <br/> <label htmlFor="selectedLocation"> Location <input value={selectedClientOrLocation.selectedLocation} id="selectedLocation" name="selectedLocation" onChange={handleChange} /> </label> </form> ) } ReactDOM.render(<Form/>,document.getElementById('root'))
 <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="root"></div>

暫無
暫無

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

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