import { NextPage } from 'next';
import React from 'react';
interface Props {
name: string;
gretting?: string; // Error: ESLint: propType "gretting" is not required, but has no corresponding defaultProps declaration.(react/require-default-props)
}
const Hello: React.FunctionComponent<Props> = ({ name, gretting = 'night' }: Props) =>
<p>Hi {name} Good {gretting}</p>;
const Home: NextPage = () => <Hello name="Jhon Doe" />;
export default Home;
Run Code Online (Sandbox Code Playgroud)
Eslint react 插件抱怨这个错误ESLint: propType "gretting" is not required, but has no corresponding defaultProps declaration.(react/require-default-props)。
根据这个 …
interface PageProps {
foo?: Function;
bar: number;
}
export class PageComponent extends React.Component<PageProps, {}> {
public static defaultProps: Partial<PageProps> = {
foo: () => alert('Did foo')
};
private doFoo() {
this.props.foo(); // Typescript Error: Object is possibly 'undefined'
}
public render(): JSX.Element {
return (
<div>
<span>Hello, world! The number is {this.props.bar}</span>
<button onClick={() => this.doFoo()}>Do the Foo</button>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法告诉 Typescriptprops.foo总是被定义?
有一个非常好的SO 问答,讨论了如何正确定义组件上 props 的类型。它甚至讨论了如何让 TS 了解无状态defaultProps组件。
然而,Typescript …
假设您像这样定义组件:
interface IProps {
req: string;
defaulted: string;
}
class Comp extends React.Component<IProps, void> {
static defaultProps = {
defaulted: 'test',
};
render() {
const { defaulted } = this.props;
return (
<span>{defaulted.toUpperCase()}</span>
);
}
}
Run Code Online (Sandbox Code Playgroud)
当你想使用它时,TypeScript需要defaulted你的道具,即使它在以下定义defaultProps:
<Comp req="something" /> // ERROR: TypeScript: prop 'defaulted' is required
Run Code Online (Sandbox Code Playgroud)
但是,如果你像这样定义道具界面:
interface IProps {
req: string;
defaulted?: string; // note the ? here
}
Run Code Online (Sandbox Code Playgroud)
然后你不能用它:
render() {
const { defaulted } = this.props; // ERROR: prop 'defaulted' possibly undefined …Run Code Online (Sandbox Code Playgroud) 问题与此非常相似,但我的重点是默认功能。(我是前端新手,如果有更正式的名称,请告诉我)
这是代码(我使用的是 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>;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,当我尝试渲染此组件时:
ReactDOM.render(<TestComp />, document.getElementById("page"));
Run Code Online (Sandbox Code Playgroud)
我有这个错误?
TS2322:类型“{}”不可分配给类型“IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNode; }> & ...'。类型 '{}' 不能分配给类型 'Readonly<{ Hello: (name: string) => void; }>'。
类型“{}”中缺少属性“Hello”。
我该如何解决这个问题?