React.forwardRef
React.forwardRef
是React中用于转发refs的高阶函数。
它允许组件接收ref
属性,并将该ref
属性转发给其子组件。
在React中,ref
属性通常用于引用DOM元素或类组件的实例。然而,在某些情况下,如果你想引用一个函数组件的实例,或者希望在父组件中操作子组件的DOM,需要使用forwardRef
。
import React, { forwardRef } from 'react';
// 子组件
const ChildComponent = forwardRef((props, ref) => {
return <input ref={ref} />;
});
// 父组件
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
componentDidMount() {
// 在父组件中获取子组件的引用
this.inputRef.current.focus();
}
render() {
return <ChildComponent ref={this.inputRef} />;
}
}
React.useImperativeHandle
React.useImperativeHandle
是React中一个用于暴露自定义实例值或实例方法给父组件的Hook。
通常情况下,父组件无法直接访问子组件内部的实例值或方法,但是通过useImperativeHandle
,可以将子组件内部的某些值或方法以指定的名称暴露给父组件。
import React, { useRef, useImperativeHandle, forwardRef } from 'react';
// 子组件
const ChildComponent = forwardRef((props, ref) => {
const inputRef = useRef();
// 定义需要暴露给父组件的方法
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
},
getValue: () => {
return inputRef.current.value;
}
}));
return <input ref={inputRef} />;
});
// 父组件
function ParentComponent() {
const childRef = useRef();
const handleButtonClick = () => {
// 调用子组件暴露的方法
console.log(childRef.current.getValue());
childRef.current.focus();
};
return (
<div>
<ChildComponent ref={childRef} />
<button onClick={handleButtonClick}>Focus Input</button>
</div>
);
}