React Native 函数式组件:父组件调用子组件方法
在 React Native 中,可以通过使用 'ref' 属性来获取子组件的实例,然后调用子组件的方法。
首先,在子组件中定义需要调用的方法:
function MyChildComponent(props, ref) {
const myMethod = () => {
console.log('My method is called!');
};
useImperativeHandle(ref, () => ({
myMethod,
}));
return (
// 子组件内容
);
}
export default forwardRef(MyChildComponent);
这里使用了 'useImperativeHandle' 和 'forwardRef',使得在父组件中能够通过 'ref' 获取到子组件的实例,并调用子组件的方法。
然后,在父组件中使用 'ref' 属性获取子组件的实例,并调用子组件的方法:
function MyParentComponent() {
const childRef = useRef();
const onButtonClick = () => {
childRef.current.myMethod();
};
return (
<View>
<MyChildComponent ref={childRef} />
<Button title="Call My Method" onPress={onButtonClick} />
</View>
);
}
在这个例子中,当按钮被点击时,会调用子组件的 'myMethod' 方法。注意,这里使用了 'useRef' 来创建 'ref' 对象,并将其传递给子组件的 'ref' 属性。
原文地址: https://www.cveoy.top/t/topic/nhei 著作权归作者所有。请勿转载和采集!