React: DRY功能组件用变量设置状态



我有一系列Input组件,只想使用一个onChange函数。

在Class组件中,我知道我可以做如下的事情来适应不同的状态:

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

在一个功能组件中,我如何只用一个onChange函数更新状态?

组件示例:

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!

因为这是一种形式,我将把状态组合成一个,用对象初始化它,然后当onChange处理程序被调用时,更新由输入id识别的属性与值。

useEffect在这里用于记录状态更新的结果。

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>

使用您在类中使用的相同方法,不同之处在于您将客户端和位置组合成一个对象,该对象将表示状态,并且您利用ids:

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>

相关内容

  • 没有找到相关文章

最新更新