[英]Default function value in React component using Typescript
问题与此非常相似,但我的重点是默认功能。 (我是前端的新手,请告诉我是否有更正式的名称)
这是代码(我正在使用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>;
}
}
然后,当我尝试渲染此组件时:
ReactDOM.render(<TestComp />, document.getElementById("page"));
我收到了这个错误;
TS2322:类型'{}'不能赋值为'IntrinsicAttributes&IntrinsicClassAttributes&Readonly <{children?:ReactNode; }>&...'。 类型'{}'不能赋值为'Readonly <{Hello:(name:string)=> void; }>”。
类型“{}”中缺少属性“Hello”。
我该如何解决这个问题?
首先,让我们修复你的例子:
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?
接口Hello?
使其成为可选,而不是使用typeof
。
编译器错误来自需要Hello
的事实,因此您需要使用:
ReactDOM.render(<TestComp Hello={() => {}} />, document.getElementById("page"));
// ^ pass Hello as a prop here
这样做会修复编译错误,但是仍然会有不正确的行为,因为您的示例中的对象TestProps
永远不会被使用。
如果你正在使用strictNullChecks
,那么你必须在类型系统中稍微运行一下,因为Hello
是一个可选属性:
if (this.props.Hello) this.props.Hello("world");
// or
this.props.Hello && this.props.Hello("world");
通过检查this.props.Hello
是否真实 ,类型缩小了(name: string) => void | undefined
(name: string) => void | undefined
to just (name: string) => void
,所以你可以调用该函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.