以下是使用功能组件执行此操作的方法:
家长
- 使用
useRef() 给子组件在父组件中的引用:
const childRef = useRef()
// ...
return (
<ChildComponent ref={childRef} />
)
...
儿童
- 将
ref 作为构造函数参数之一传递:
const ChildComponent = (props, ref) => {
// ...
}
- 从
'react' 库中导入useImperativeHandle 和forwardRef 方法:
import React, { useImperativeHandle, forwardRef } from 'react'
- 使用
useImperativeHandle 将函数绑定到ref 对象,这将使父对象可以访问这些函数
这些方法在内部不可用,因此您可能希望使用它们来调用内部方法。
const ChildComponent = (props, ref) => {
//...
useImperativeHandle(ref, () => ({
// each key is connected to `ref` as a method name
// they can execute code directly, or call a local method
method1: () => { localMethod1() },
method2: () => { console.log("Remote method 2 executed") }
}))
//...
// These are local methods, they are not seen by `ref`,
const localMethod1 = () => {
console.log("Method 1 executed")
}
// ..
}
- 使用
forwardRef导出子组件:
const ChildComponent = (props, ref) => {
// ...
}
export default forwardRef(ChildComponent)
把它们放在一起
子组件
import React, { useImperativeHandle, forwardRef } from 'react';
import { View } from 'react-native'
const ChildComponent = (props, ref) => {
useImperativeHandle(ref, () => ({
// methods connected to `ref`
sayHi: () => { sayHi() }
}))
// internal method
const sayHi = () => {
console.log("Hello")
}
return (
<View />
);
}
export default forwardRef(ChildComponent)
父组件
import React, { useRef } from 'react';
import { Button, View } from 'react-native';
import ChildComponent from './components/ChildComponent';
const App = () => {
const childRef = useRef()
return (
<View>
<ChildComponent ref={childRef} />
<Button
onPress={() => {
childRef.current.sayHi()
}}
title="Execute Child Method"
/>
</View>
)
}
export default App
Expo Snacks 上有一个互动演示:
https://snack.expo.dev/@backupbrain/calling-functions-from-other-components
这个解释是从这个TutorialsPoint article修改的