我正在尝试为https://github.com/callstack/react-native-fbads的原生广告部分编写打字。到目前为止,我已经提出以下建议:
declare module 'react-native-fbads' {
import { Component } from 'react';
export class NativeAdsManager {
constructor(placementId: string, numberOfAdsToRequest: number);
}
export interface NativeAd {
icon?: string;
coverImage?: string;
title?: string;
subtitle?: string;
decription?: string;
callToActionText?: string;
socialContext?: string;
}
interface IWithAd {
nativeAd: NativeAd;
}
interface IWithManger {
adsManager: NativeAd;
}
export function withNativeAd<T, S>(comp: Component<T & IWithAd, S>): Component<T & IWithManger, S>;
}
但是当我尝试将它与以下组件一起使用时:
import * as React from 'react';
import { View } from 'react-native';
import { NativeAd, withNativeAd } from 'react-native-fbads';
interface IProps {
myProp: number;
nativeAd: NativeAd;
}
class AdComponent extends React.Component<IProps> {
public render() {
return (
<View>
</View>
);
}
}
export default withNativeAd(AdComponent);
我收到以下错误:
Argument of type 'typeof AdComponent' is not assignable to parameter of type 'Component<IWithAd, {}>'.
Property 'setState' is missing in type 'typeof AdComponent'
这里最重要的是&#34; withNativeAd&#34;应该键入一个函数,该函数将React组件带有一些属性+ a&#34; nativeAd&#34; property并返回另一个具有这些属性的React组件 - &#34; nativeAd&#34; +&#34; adsManager&#34;。显然我做错了,但我不知道正确的方法是什么,错误没有帮助。
编辑:
使用ComponentClass更改为以下内容:
declare module 'react-native-fbads' {
import { ComponentClass } from 'react';
export class NativeAdsManager {
constructor(placementId: string, numberOfAdsToRequest: number);
}
export interface NativeAd {
icon?: string;
coverImage?: string;
title?: string;
subtitle?: string;
decription?: string;
callToActionText?: string;
socialContext?: string;
}
interface IWithAd {
nativeAd: NativeAd;
}
interface IWithManger {
adsManager: NativeAd;
nativeAd: undefined;
}
export function withNativeAd<P>(comp: ComponentClass<P & IWithAd>): ComponentClass<P & IWithManger>;
}
使之前的错误消失,但抱怨我没有向&#34; nativeAd&#34;分配任何内容。在创建包装对象的实例时。相反,应该只需要&#34; adsManager&#34;不是&#34; nativeAd&#34;因为包装的组件会生成&#34; nativeAd&#34;使用&#34; adsManager&#34;。
答案 0 :(得分:0)
当我遇到类似的问题时,我发现使用react.componentClass
作为包装组件输入修复了错误:
export const withNativeAd = <TProps, TState>(WrappedComponent: React.ComponentClass<IWithAd> ): React.ComponentClass<IWithAd> => {
return class extends React.Component<IWithAd, TState> {
render() {
return (
<WrappedComponent {...this.props} />
)
}
}
}