你遇到的问题与React中refs的处理方式有关。当在类似FormRow的子组件中使用ref时,需要正确地转发它才能按预期工作。
问题在于你如何在FormRow组件中传递ref属性。在函数式组件中,相对于普通props,refs的处理方式有所不同。你不能直接传递ref prop,而应该使用React.forwardRef来妥善处理。
以下是修改FormRow组件以正确处理ref的方法:
import React from "react";
const FormRow = React.forwardRef(
(
{ type, name, labelText, defaultValue = "", onChange, onBlur, max },
ref
) => {
return (
<div className="form-row">
<label htmlFor={name} className="form-label">
{labelText || name}
</label>
<input
autoComplete="off"
type={type}
id={name}
name={name}
className="form-input"
defaultValue={defaultValue}
required
onChange={onChange}
onBlur={onBlur}
max={max}
min="0"
ref={ref}
/>
</div>
);
}
);
export default FormRow;
然后,在你的AddProject组件中,你可以继续像之前那样使用useRef:
const refContainer = useRef(null);
const name = refContainer.current?.value; // 通过current访问值
useEffect(() => {
console.log(name);
}, [name]); // 将name包含在依赖数组中以便记录变化
这个改动将允许你在AddProject组件中使用useRef Hook正确地访问输入框的值。