这是一个使用useImperativeHandle
钩子的代码片段示例:
import React, { useRef, useImperativeHandle, forwardRef } from 'react';
// 子组件
const ChildComponent = forwardRef((props, ref) => {
const inputRef = useRef();
// 在子组件中定义暴露给父组件的方法
useImperativeHandle(ref, () => ({
focusInput: () => {
inputRef.current.focus();
},
// 其他方法...
}));
return (
<input ref={inputRef} type="text" />
);
});
// 父组件
const ParentComponent = () => {
const childRef = useRef();
const handleClick = () => {
// 调用子组件暴露的方法
childRef.current.focusInput();
};
return (
<div>
<ChildComponent ref={childRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
};
export default ParentComponent;
在这个示例中,父组件ParentComponent
包含了一个子组件ChildComponent
和一个按钮。子组件中包含一个输入框,并使用useImperativeHandle
钩子将输入框的focus
方法暴露给父组件。
父组件中通过useRef
创建了一个引用childRef
,并将它传递给子组件的ref
属性。当点击按钮时,调用childRef.current.focusInput()
来触发子组件中暴露的focusInput
方法,实现对输入框的聚焦操作。