reactjs - 在 React 中使用 forwardRef 或仅将 ref 作为 prop 传递之间的区别及其对 useImperitaveHandle 的影响
问题描述
React 文档为 forwardRef 提供了以下示例
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>;
但是当 ref 作为 prop 传递而不是通过 ForwardRef 传递时,这段代码也可以工作
const FancyButton = (props) => (
<button ref={props.testRef} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton testRef={ref}>Click me!</FancyButton>;
如果两者的工作方式相同,那么使用 ForwardRef 的原因是什么?
当 ref 作为道具传递时,也可以使用 useImperitaveHandle Hook 吗?
解决方案
推荐阅读
- c++ - 从指向其成员类的指针打印字符串
- r - 从R转换两个列表中的一个列表
- python - 为什么 64 位 `pip install MySQL-python` 指的是 `C:\Program Files (x86)\`?
- sql - 使用子字符串在sql中分隔名称
- ios - Flutter登录Apple无法在iOS模拟器上运行(无限加载器)
- mysql - 仅当日期有效时才在 MySQL 中插入日期
- javascript - 了解 React JS 中的 .env 文件和环境变量
- django-rest-framework - 使用 postman 或 django-rest-framework 测试
- sql - SQL 语句的建议格式
- matlab - 在 Matlab 中用计数命名