![](/img/trans.png)
[英]How to change state value when input is checked with useState hook
[英]How to make functions that change the state via useState hook reusable?
假设我有以下代码用于更改输入值,它会更新组件的 state:
const handleInputChange = e => {
let value = e.target.value;
let name = e.target.name;
let type = e.target.type;
// some other code
setInput(nextState);
};
但是,由于我有不同的组件使用相同的 function,因此我想将其设为可导出的实用程序 function。 但是它有来自useState
钩子的“setInput” function 调用。
我是否应该将setInput
作为参数传递给每个handleInputChange()
调用,例如:
onChange={e => handleInputChange(e, setInput)}
或者有没有更好的方法来处理这个?
如果您正在创建自定义钩子,则可以在其中调用其他钩子。 所以你可以只在钩子中检索setInput
而不是在那里传递它:
const useCustomHook = (initialValue) => {
const [input, setInput] = useState(initialValue);
// ...
const handleInputChange = e => {
let value = e.target.value;
let name = e.target.name;
let type = e.target.type;
// some other code
setInput(nextState);
};
return handleInputChange;
}
此input
将绑定到调用 useCustomHook 的组件的useCustomHook
。
编辑:
将@Shota 的答案与这个答案相结合,您可以使用useState
钩子创建一个组件来在内部处理 state :
const CustomInput(initialState) => {
const [input, setInput] = useState(initialValue);
const handleInputChange = e => {
// ...
setInput(nextState);
};
return (<input type="text" onChange={handleInputChange} />);
}
要在外部世界中使用input
,只需从钩子中返回它:
useCustomHook = () => {
// ...
return {
handleInputChange,
input
}
}
您可以使用 on change function 属性创建一个全新的可重用组件。
import React from 'react';
const CommonInput = ({handleChange}) => {
const handleInputChange = e => {
let value = e.target.value;
let name = e.target.name;
let type = e.target.type;
// some other code
setInput(nextState);
handleChange(nextState);
};
return (<input type="text" onChange={handleInputChange} />);
}
export default CommonInput;
我们可以在任何我们想要的地方重用它:
import React from 'react';
const Parent = (props) => (
<CommonInput handleChange={nextStateData => {}}/>
);
export default Parent;
通常,我更愿意创建一个内部具有某些功能的新组件,而不是仅重用函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.