javascript - 为什么 ref 总是为空?
问题描述
我在下面有一个组件,在第一次渲染时我有正确ref
的输入,但是我总是得到null
,下一次渲染,请告诉我为什么?ref
通过 props 传递给 input:
const inputRef = useRef(null);
useEffect(() => {
setTimeout(() => {
if (inputRef.current) {
inputRef.current.focus();
}
});
}, [inputRef]);
render() {
return(
<div>
<FirstComponent />
{({ selectedItem, items }) => (
<SecondCompontnt
inputRef={inputRef}
items={items}
onSelect={onSelect}
value={selectedItem}
/>
)}
</div>
)
}
解决方案
一旦您ref
在其一个子组件的父组件中拥有了 ,那么您需要应用所谓的Forwarding Ref 技术,如文档所述:
Ref 转发是一种通过组件自动将 ref 传递给它的一个子组件的技术。对于应用程序中的大多数组件,这通常不是必需的。
假设您在父组件中具有以下内容:
const childDivRef = useRef(null);
return <>
<ChildComponent ref={childDivRef} />
</>
然后你需要在子组件中有如下:
import React, { forwardRef } from 'react';
const ChildComponent = forwardRef((props, ref) => {
return <div ref={ref} className="child-component">
<h3>Child component</h3>
</div>
})
如果您需要一个工作示例,请找到我之前创建的这个 GitHub 存储库:https ://github.com/norbitrial/react-forwarding-ref-example
我希望这有帮助!
推荐阅读
- node.js - 我需要 Firebase Web 应用的后端吗?
- java - 在 Ubuntu 16 Docker 容器(Oracle JDK 8 和 MVN)中构建 Android 应用程序
- apache-kafka - Kafka Streams 在监听具有多个分区的主题时如何确保处理所有相关数据?
- c++ - 使用 findfirstfile 和 findnextfile 在子目录中搜索
- java - CDI 不适用于 Tomcat8 + JSF Mojarra 2.3.8 + Primefaces 8.0 + WELD
- javascript - 无法在 Calendar Expo React Native 中创建事件
- python - Python - 如何将 Windows 路径写入 json 文件?
- facebook - 如何知道之前是否已授权 facebook 登录?
- c++ - 如何在不创建新线程的情况下异步执行代码
- react-native - 模态内的反应原生 Flatlist 有时不显示数据