基础代码
import React from 'react';
interface Prop {
children: React.ReactNode
}
class Person extends React.Component<Prop, {}> {
constructor(props: Prop) {
super(props);
this.state = {};
}
render() {
return (
<div>
// 这个地方报错
{ this.props.children({ x: 30, y: 40 }) }
</div>
);
}
}
报错内容
(property) React.Component<Prop, {}, any>.props: Readonly<Prop> & Readonly<{
children?: React.ReactNode;
}>
不能调用可能是 "null" 或“未定义”的对象。ts(2723)
(property) children: React.ReactNode
不能调用可能是 "null" 或“未定义”的对象。ts(2723)
此表达式不可调用。
不可调用 "string | number | boolean | {} | ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)> | ReactNodeArray | ReactPortal" 类型的任何组成部分。ts(2349)
另一种写法,不报错
import React from 'react';
interface Prop {
children: React.ReactNode
}
class Person extends React.Component<Prop, {}> {
constructor(props: Prop) {
super(props);
this.state = {};
}
render() {
const props: any = this.props;
return (
<div>
// 这样不会报错
{ props.children({ x: 30, y: 40 }) }
</div>
);
}
}
问题
- 为什么报错,我不是已经给他做了类型声明了吗
- 怎么解决
- react + ts 有没有什么好的文档推荐
** 勿喷我,觉得问题简单,不愿意回复的请退出去 **