ref 属性未传递,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: "" })}
/>
...
,我想使用它,如果我使用普通的 TextInput 则没有问题,但是当我尝试使用我的 CustomInput 时, 我得到错误
类型错误:null不是对象(评估“inputRef.current.focus”)
我不明白为什么 ref={props.ref} 没有完成这项工作。我认为 ref 也会传递给我的组件。如何正确传递ref?
I am making a custom input component
const CustomInput = (props) => {
console.log(props);
return (
<TextInput
{...props}
ref={props.ref}
placeholder={props.placeholder}
style={{ ...styles.text, ...props.style }}
/>
);
};
in the file I want to use it I have
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: "" })}
/>
...
If I am using normal TextInput there is no problem, but when I try to use my CustomInput,
i get the error
TypeError: null is not an object (evaluating 'inputRef.current.focus')
I don't get why ref={props.ref} is not doing the job. I thought that ref will be passed to my component too. How to pass ref properly ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ref 不在
props
内部。使用ref
作为 prop 时,应使用forwardRef()
创建 FunctionComponent,该函数采用具有两个参数的函数:props
和参考
。这是文档 https://reactjs.org/docs/forwarding-refs.html< 中的示例/a>
The ref is not inside of
props
. When usingref
as a prop, the FunctionComponents should be created withforwardRef()
which takes a function that has two arguments,props
andref
.Here's the example from the documentation https://reactjs.org/docs/forwarding-refs.html
因此,通过这个,我们可以确定是否希望它选择输入,
原因是 ref 无法向下传递,因为它是对该组件的引用,除非您使用 React.forwardRef 但这是一种没有forwardRef
import { useEffect 的 方法, useRef } 来自“反应”;
导入“./styles.css”;
或与forwardRef
So with this we can determine if we want it to select the input or not
the reason is that the ref cannot be passed down as it is a ref to that component unless you use React.forwardRef but this is a way without forwardRef
import { useEffect, useRef } from "react";
import "./styles.css";
OR with forwardRef