[英]Input value received on props doesn't change
有一個輸入表格:
<input type="number" value={propsValue} onChange={changeValue} />
propsValue
通過 props 在組件中接收。 為了能夠更改輸入表單中的值, changeValue
應該如何更改值?
編輯:意識到我復制粘貼了實用程序 function 的硬代碼導入路徑。 只需用您的實用程序 function 路徑替換即可。
對於功能組件,使用輔助實用程序 function 到 map 輸入到 state 會很有用。 這是我使用的設置(非常基本)。 我有一個useForm.js
文件,它導出useForm
function:
import { useState } from 'react';
export default function useForm(defaults) {
const [values, setValues] = useState(defaults);
function updateValue(e) {
if (e.target.type === 'number') {
e.target.value = parseInt(e.target.value);
}
setValues({ ...values, [e.target.name]: e.target.value });
}
return { values, updateValue };
}
然后在我想使用 a 表單的地方,我可以這樣做:
import useForm from '../utils/useForm';
export default function MyComponent(props) {
const { values, updateValue } = useForm({
name: props.inputValue1,
email: props.inputValue2
});
return (
<form>
<label htmlFor="name">
Name
<input
type="text"
name="name"
id="name"
value={values.name}
onChange={updateValue}
/>
</label>
<label htmlFor="email">
Email
<input
type="email"
name="email"
id="email"
value={values.email}
onChange={updateValue}
/>
</label>
</form>
)
}
所以你看我使用幫助器 function 將輸入綁定到組件的 state。 您需要確保您的輸入名稱與您在組件文件中調用useForm
時傳遞的名稱屬性相匹配。
順便感謝 Wes Bos 的幫助者 function。
像這樣的東西。
// hooks const {useState} = React; function Input(props){ return <input type="number" value={props.value} onChange={() => props.onChange(event)} /> }; function App(){ const [value, setValue] = useState(''); function onChange(event){ setValue(event.target.value) } return ( <div> <p>Value: {value}</p> <Input value={value} onChange={onChange}/> </div> ); }; // Render ReactDOM.render( <App />, document.getElementById("react") );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="react"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.