React forwardRef 用法案例分析
作者:一颗不甘坠落的流星
这篇文章主要介绍了React forwardRef用法,forwardRef允许你的组件使用ref将一个DOM节点暴露给父组件,本文结合案例分析给大家讲解的非常详细,需要的朋友可以参考下
React.forwardRef 会创建一个React组件,这个组件能够将其接受的 ref 属性转发到其组件树下的另一个组件中。这种技术并不常见,但在以下两种场景中特别有用:
- 转发 refs 到 DOM 组件
- 在高阶组件中转发 refs
本文重点介绍下React forwardRef 用法。
用法
forwardRef:允许你的组件使用 ref 将一个 DOM 节点暴露给父组件。
import { forwardRef } from 'react';
const MyInput = forwardRef((props, ref) => {
// ...
});案例分析:ref 属性是 React 的特殊属性,不能直接使用。
import {useRef} from 'react'
function InputCom({ref}) {
return (
<input type='text' ref={ref} />
)
}
function App() {
const inpRef = useRef(null)
const focus = () => {
inpRef.current?.focus()
}
return (
<>
<InputCom ref={inpRef} />
</>
)
}上面就会弹出报错信息:
Warning: InputCom: `ref` is not a prop. Trying to access it will result in `undefined` being returned.
If you need to access the same value Within the child component, you should pass it as a company's prop.
// 警告:InputCom: 'ref不是一个prop。试图访问它将导致返回undefine。如果你需要在子组件中访问相同的值,你应该把它作为公司的prop传递。
如果想传递 ref,这时候就要借助 forwardRef 函数
import { forwardRef, useRef } from "react";
const InputCom = forwardRef((props, ref) => {
return <input type="text" ref={ref} />;
});
export default function ProRef() {
const inpRef = useRef(null);
const focus = () => {
inpRef.current?.focus();
};
return (
<>
<InputCom ref={inpRef} />
<button onClick={focus}>focus</button>
</>
);
}到此这篇关于React forwardRef 用法的文章就介绍到这了,更多相关React forwardRef 用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
