使用Typescript的React组件中的默认函数值 [英] Default function value in React component using Typescript

查看:118
本文介绍了使用Typescript的React组件中的默认函数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题与 this ,但是我的重点是默认功能.(我是前端的新手,请给我一个更正式的名称)

The question is very similar to this, but mine is focused on the default function. (I'm new to front-end, please let me know if there's a more official name for it)

这是代码(我正在使用TypeScript 2.5):

This is the code (I'm using TypeScript 2.5):

export const TestProps = {
    Hello: (name: string) => {
        console.log(name);
    }
}

type TestPropsType = typeof TestProps;

export class TestComp extends React.Component<TestPropsType, {}>{    
    public render() {
        this.props.Hello("world");
        return <div>test</div>;
    }
}

然后,当我尝试渲染此组件时:

Then, when I try to render this component:

ReactDOM.render(<TestComp />, document.getElementById("page"));

我遇到了这个错误;

TS2322:类型"{}"不可分配给类型"IntrinsicAttributes&IntrinsicClassAttributes&只读< {儿童?:ReactNode;}>&...'.类型'{}'不能分配给类型'Readonly< {Hello:(name:string)=> void;}>'.

TS2322: Type '{}' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNode; }> & ...'. Type '{}' is not assignable to type 'Readonly<{ Hello: (name: string) => void; }>'.

类型"{}"中缺少属性"Hello".

Property 'Hello' is missing in type '{}'.

如何解决此问题?

推荐答案

首先,让我们修复您的示例:

First, let's fix your example:

interface TestProps {
    Hello?: { (name: string): void };
}

export class TestComp extends React.Component<TestProps, {}> {    
    public static defaultProps: Partial<TestProps> = {
        Hello: name => console.log(name)
    };

    public render() {
        this.props.Hello("world");
        return <div>test</div>;
    }
}

您之前编写的方式意味着您的组件看不到 TestProps (它不是从任何地方传入的),并且 Hello 是必需的支柱.我在 Hello?中使用了一个接口,使其成为可选的,而不是使用 typeof .

The way that you had it written before meant that your component couldn't see TestProps (it wasn't passed in from anywhere) and that Hello was a required prop. I used an interface with Hello? to make it optional, rather than using typeof.

编译器错误源于需要 Hello 的事实,因此您将需要使用:

The compiler error came from the fact that Hello was required, so you would have needed to use:

ReactDOM.render(<TestComp Hello={() => {}} />, document.getElementById("page"));
                       // ^ pass Hello as a prop here

这样做可以解决编译错误,但是仍然会导致行为不正确,因为示例中的对象 TestProps 将永远不会使用.

Doing this would fix the compile error, but you would still be left with incorrect behaviour, as the object TestProps in your example would never be used.

如果您使用的是 strictNullChecks ,那么您将不得不处理类型系统,因为 Hello 是一个可选属性:

If you are using strictNullChecks, then you will have to work your way around the type system a little bit, since Hello is an optional property:

if (this.props.Hello) this.props.Hello("world");
// or
this.props.Hello && this.props.Hello("world");

通过检查 this.props.Hello 是否为 truthy ,将类型缩小为(name:string)=>无效undefined 改为(name:string)=>无效,因此您可以调用该函数.

By checking whether this.props.Hello is truthy, the type is narrowed from (name: string) => void | undefined to just (name: string) => void, so you can call the function.

这篇关于使用Typescript的React组件中的默认函数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆