簡體   English   中英

我想在反應中使用自定義鈎子

[英]i want use custom hooks in react

我的問題是我創建了自定義鈎子,並使用表單鈎子跟蹤輸入文本並更新了狀態。 我想在單擊按鈕后使用該自定義鈎子提交狀態下的輸入值,而我被困在這里...


export const useForm = (initialValue) => {
    const [value, setValue] = useState(initialValue);
    return [value, e => 
    setValue({
        ...value, [e.target.name] : e.target.value
    })];
}

這是我的自定義鈎子

 <form onSubmit={updateCityName}>
            <div className="form">
                <div className="input-field">
                    <i className="material-icons prefix">location_on</i>
                    <input id="icon_prefix" type="text" name="cityName" value={value.cityName} onChange={handleChange} className="validate" />
                    <label htmlFor ="icon_prefix">City Name</label>
                </div>
                    <button className="btn waves-effect waves-light" type="submit" name="action">Submit</button>
            </div>
        </form>

這是我的表格,這是功能

const updateCityName = e => {
    e.preventDefault();
    handleChange('what i must here type for update state???');
  }

您可以在此示例中執行以下操作: https : //codesandbox.io/s/ecstatic-tree-2893r

您具有useForm來設置和更新表單狀態。 然后,您具有提交狀態的第二種狀態。

我使用了2種不同的狀態:第一種useForm處理輸入的更改。

一旦用戶單擊按鈕,第二狀態即保持提交的信息。 當然,在實際情況下,您將對提交的信息進行其他操作,例如調用網絡服務等。

暫無
暫無

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

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