React 父组件调用子组件的方法
useImperativeHandle(ref, createHandle, [deps])
useImperativeHandle 可以让你在使用 ref 时自定义暴露给父组件的实例值。在大多数情况下,应当避免使用 ref 这样的命令式代码。useImperativeHandle 应当与 forwardRef 一起使用:
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
详细用法
子组件
- 使用
forwardRef
包裹组件
const HPickItem = React.forwardRef(() => {
....
})
- 接受子组件传入的
ref
const HPickItem = React.forwardRef((props,ref) => {
return (
<View className="sliding-container" ref={ref}}}>
{
...
}
</View>
)
})
- 对外暴露方法
const HPickItem = React.forwardRef((props,ref) => {
...
// 对外暴露的方法
const next = () => {
setMove(pre => pre - itemHeight)
}
const prev = () => {
setMove(pre => pre + itemHeight)
}
//用useImperativeHandle暴露一些外部ref能访问的属性
useImperativeHandle(ref, () => {
// 需要将暴露的接口返回出去
return {
next,
prev
};
})
....
return (
<View className="sliding-container" ref={ref}}}>
{
...
}
</View>
)
})
父组件
- 创建ref
const controlRef = useRef(null)
....
<HPickItem ref={controlRef}></HPickItem>
- 使用子组件的方法
controlRef.current.next()
controlRef.current.prev()