ref prop 未传递,TypeError:null 不是对象(评估 'inputRef.current.focus')



我正在制作一个自定义输入组件


const CustomInput = (props) => {
console.log(props);
return (
<TextInput
{...props}
ref={props.ref}
placeholder={props.placeholder}
style={{ ...styles.text, ...props.style }}
/>
);
};

在我想使用它的文件中,我有

const ForgottenPasswordScreen = (props) => {
...
const inputRef = React.createRef();
useEffect(() => {
inputRef.current.focus();
}, []);
...
<CustomInput
placeholder={"E-mail..."}
value={email.value}
ref={inputRef}
onChangeText={(text) => setEmail({ value: text, error: "" })}
/>
...

如果我使用普通的文本输入,则没有问题,但是当我尝试使用自定义输入时, 我收到错误

TypeError: null 不是对象(评估 'inputRef.current.focus')

我不明白为什么 ref={props.ref} 没有完成这项工作。我以为 ref 也会传递给我的组件。如何正确传递参考?

ref 不在props内。当使用ref作为道具时,应该使用forwardRef()创建函数组件,该函数采用具有两个参数的函数,propsref

下面是文档 https://reactjs.org/docs/forwarding-refs.html 中的示例

const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

因此,有了这个,我们可以确定是否希望它选择输入

原因是引用不能传递下来,因为它是该组件的引用,除非您使用 React.forwardRef,但这是一种没有 forwardRef 的方法

从 "react" 导入 { useEffect, useRef }; 导入"./样式.css";

const InsantSelectInput = (props) => {
const inputRef = useRef(null)
useEffect(() => {
if(inputRef && inputRef.current)
inputRef.current.focus()
}, [inputRef])
return <input {...props} ref={inputRef} placeholder={props.placeholder} />;
}
const CustomInput = (props) => {
return <>
{props.isSelectedInput && <InsantSelectInput {...props} />}
{!props.isSelectedInput && <input {...props}  placeholder={props.placeholder} />}
</>
};
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<CustomInput
placeholder={"E-mail..."}
value={""}
isSelectedInput
onChangeText={(text) => console.log({ value: text, error: "" })}
/>
</div>
);
}

或与前向引用

const CustomInput = React.forwardRef((props, ref) => {
return <>
<TextInput
{...props}
ref={ref}
placeholder={props.placeholder}
style={{ ...styles.text, ...props.style }}
/>
});
const ForgottenPasswordScreen = (props) => {
...
const inputRef = React.createRef();
useEffect(() => {
inputRef.current.focus();
}, []);
...
<CustomInput
placeholder={"E-mail..."}
value={email.value}
ref={inputRef}
onChangeText={(text) => setEmail({ value: text, error: "" })}
/>
...

最新更新