React Native TypeScript:如何在函数组件及其他组件中使用接口函数
在FunctionComponent中使用Props中的函数及跨组件调用方法
一、在当前FunctionComponent中使用someFunction
在FunctionComponent里,传入的props对象包含了接口IProps定义的所有属性,直接通过props.someFunction即可访问并调用这个函数,TypeScript会自动做类型校验。
示例代码:
interface IProps { someFunction(): Promise<boolean>; } // 注意:FunctionComponent不是类,组件名建议用SomeComponent而非SomeClass const SomeComponent: FC<IProps> = props => { // 示例:在点击事件中调用函数 const handleExecute = async () => { try { const result = await props.someFunction(); console.log("函数执行结果:", result); } catch (err) { console.error("函数调用失败:", err); } }; return <button onClick={handleExecute}>执行someFunction</button>; };
二、在其他组件中调用someFunction
要在其他组件调用这个函数,核心是让函数的实现能被多个组件访问到,常见的实现方式有两种:
1. 组件层级传递(Props Drilling)
如果其他组件和SomeComponent有共同的父组件,可以在父组件中定义someFunction的具体实现,再分别传递给需要的子组件:
// 父组件:定义函数实现并传递给子组件 const ParentComponent = () => { const someFunction = async (): Promise<boolean> => { // 这里写具体业务逻辑,比如接口请求、状态处理等 return new Promise(resolve => setTimeout(() => resolve(true), 1000)); }; return ( <div> <SomeComponent someFunction={someFunction} /> <OtherComponent someFunction={someFunction} /> </div> ); }; // 其他组件:声明Props并使用函数 interface IOtherProps { someFunction(): Promise<boolean>; } const OtherComponent: FC<IOtherProps> = props => { const handleCall = async () => { const res = await props.someFunction(); console.log("其他组件调用结果:", res); }; return <button onClick={handleCall}>在其他组件执行函数</button>; };
2. 使用Context API共享函数(适合深层组件或多组件共享)
如果组件层级较深,或者多个无直接关联的组件需要使用这个函数,用React Context可以避免多层Props传递:
import { createContext, useContext, FC, ReactNode } from 'react'; // 创建Context,指定函数类型 const FunctionContext = createContext<(() => Promise<boolean>) | undefined>(undefined); // Context提供者组件,包裹需要共享函数的组件树 const FunctionProvider = ({ children }: { children: ReactNode }) => { const someFunction = async (): Promise<boolean> => { return true; // 具体实现逻辑 }; return ( <FunctionContext.Provider value={someFunction}> {children} </FunctionContext.Provider> ); }; // 在SomeComponent中通过Context获取函数 const SomeComponent: FC = () => { const someFunction = useContext(FunctionContext); // 可选:添加校验确保组件在Provider内使用 if (!someFunction) throw new Error("SomeComponent必须在FunctionProvider中使用"); const handleClick = async () => { const result = await someFunction(); console.log("调用结果:", result); }; return <button onClick={handleClick}>执行函数</button>; }; // 在其他组件中同样通过Context获取函数 const OtherComponent: FC = () => { const someFunction = useContext(FunctionContext); if (!someFunction) throw new Error("OtherComponent必须在FunctionProvider中使用"); const handleCall = async () => { const res = await someFunction(); console.log("其他组件调用结果:", res); }; return <button onClick={handleCall}>在其他组件执行函数</button>; }; // 根组件中使用Provider包裹 const App = () => { return ( <FunctionProvider> <SomeComponent /> <OtherComponent /> </FunctionProvider> ); };
内容的提问来源于stack exchange,提问作者IOSDev
相关产品推荐
相关产品推荐

