【发布时间】:2021-09-22 17:56:50
【问题描述】:
我有一种情况,我创建了一个输入组件。这是一个自定义组件,我想访问用户在父组件(我正在使用它的地方)的此输入中输入的值。
我正在从这个输入组件转发 ref,但父组件接收的是完整的输入而不是值。我如何使用该值。 下面是我的代码。
输入.tsx
interface AuxProps {
id :''
}
const Input = React.forwardRef<HTMLInputElement,AuxProps>((props, ref) => {
return (
<input
id={props.id}
ref = {ref}
defaultValue = '1'
type='number'
></input>
);
});
export default Input;
HeaderComponent.tsx
const HeaderComponent= () => {
const inputAmount = useRef<HTMLInputElement>(null);
const addProductHandle = (event: any) => {
event.preventDefault();
console.log(inputAmount.current.value); //<----Error:- object is possibly null
};
return (
<form className={classes["form"]}>
<Input id="1s" ref={inputAmount}></Input>
<button onClick={addProductHandle}> + ADD </button>
</form>
);
};
export default HeaderComponent;
不知道如何使用这个 ref 值。
【问题讨论】:
标签: reactjs typescript react-redux components ref