reactjs - 使用 forwardRef 中的 ref 时,ref.current 始终未定义
问题描述
import React, { useRef } from "react";
import { render } from "react-dom";
const styles = {
fontFamily: "sans-serif",
textAlign: "left"
};
const Wrapper = () => {
const ref = useRef();
return <App ref={ref} />;
};
const App = React.forwardRef(
({ placeHolder, onNameSelected, error, onSuggestion }, ref) => {
ref.current.setAttribute("he-de-data", "");
return (
<div style={styles}>
<h4>Username</h4>
<input ref={ref} />
</div>
);
}
);
render(<Wrapper />, document.getElementById("root"));
这是一个可以帮助您的沙箱:
我有以下代码,但 ref.current 未定义。我需要使用 refforwardRef
并使用该 ref 向 DOM 添加一些属性。但是,ref.current
始终是undefined。有什么特别的原因吗?
解决方案
首先,您错误地使用了 ref 和 forwardRef 。
使用 forwardRef 是因为无法实例化功能组件,因此如果您将 ref 分配给您创建的任何功能组件,它将为空。forwardRef 所做的是将 ref 转发到它正在包装的组件,然后您可以将其分配给组件内的任何 html 元素,在那里您可以从PARENT访问 DOM 。
您要做的是从组件本身而不是父级中设置属性。所以不需要前向参考
const Comp =({ placeHolder, onNameSelected, error, onSuggestion }) => {
const inputRef = useRef(null);
useEffect(()=>{
if(inputRef.current!==null)
inputRef.current.setAttribute("he-de-data", "");
},[]);
return (
<div style={styles}>
<h4>Username</h4>
<input ref={inputRef} />
</div>
);
}
https://codesandbox.io/embed/react-16-v0kn4?fontsize=14&hidenavigation=1&theme=dark
推荐阅读
- java - android图像裁剪器无法正常工作
- sql - 查询每个客户具有多行(销售漏斗)事件的规范化表
- java - 5分钟后自动令牌过期Java
- python - 在这个 python 函数定义中是否没有正确使用运算符?
- python - ImportError:无法导入名称“center_net_hourglass_feature_extractor”
- angular - v9升级后Angular应用程序冻结/无限加载而没有错误
- python - 试图跨多个表获取一组数据
- scala - 如何在 ScalaFX 中动态地将节点添加到 VBox
- git - 强行从另一个分支复制一个分支?
- c# - 检查 nullable int 是否为 null,如果是,则将 null 插入 SQL