英文:
useRef and value at the same time?
问题
以下是翻译好的代码部分:
type Props = {
value?: number;
onChangeState?: any;
};
const InputField = forwardRef<HTMLInputElement, Props>((onChangeState, value }, ref) => {
return (
<>
<StyledInputField
type="number"
value={value || 0}
ref={ref}
onChange={(e) => onChangeState && onChangeState(e.target.valueAsNumber)}
/>
</>
);
});
export default InputField;
const MyComponent = () => {
const inputValue = 10;
const inputValueRef = useRef(null);
return (
<InputField value={inputValue} ref={inputValueRef} />
)
}
如果您有任何其他问题或需要进一步的帮助,请告诉我。
英文:
I have an input field component that looks like this:
type Props = {
value?: number;
onChangeState?: any;
};
const InputField = forwardRef<HTMLInputElement, Props>(( onChangeState, value }, ref) => {
return (
<>
<StyledInputField
type="number"
value={value || 0}
ref={ref}
onChange={(e) => onChangeState && onChangeState(e.target.valueAsNumber)}
/>
</>
);
}
);
export default InputField;
In my other component, where I use it, I do something like this:
const MyComponent= () => {
const inputValue = 10
const inputValueRef = useRef(null);
return (
<InputField value={inputValue} ref={inputValueRef} />
)
}
The issue is, when I need to call the InputField
value with inputValueRef.current.value
, well, I get that value (in this case predefined as 10, but it could be some other already loaded value). However, if I want to change the value of the InputField
and use the new value, nothing happens. I can't do backspace, I can't highlight everything and just type in a new value. So basically I am stuck with the predefined value. How can I fix that?
I know I could use useState
. But I really don't want to re-render everytime a new character is written into the InputField
. I just want to get the current value of the InputField
when I click a button, and then show the current value as well, and change it if needed.
答案1
得分: 1
如果我理解你的意思正确的话,你想要将你的输入框作为一个不受控制的组件来使用(换句话说,你希望让输入框使用浏览器原生的处理方式,只是在你的React代码中提供一个初始值,并在完成后读取值),所以你需要指定一个defaultValue
而不是value
。
然而,如果你所说的“如果需要的话更改它”是指你想要能够在需要时以编程方式更改它,那就比较棘手。你可以使其工作(通过更改React键以强制重新创建组件,或通过引用操作),但在这种情况下,最好使用受控组件。
英文:
If I understand you correctly, you're wanting to use your input as an uncontrolled component (in other words, you want to let the input do its browser-native handling, with your React code merely providing an initial value and reading a value out when done), so you'll need to specify a defaultValue
instead of a value
.
However, if by "change it if needed" you mean that you want to be able to programmatically change it when needed, that's trickier. You can make it work (via changing React keys to force the component to be recreated, or by ref manipulation), but you're better off using a controlled component at that point.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论