Reactjs,Typescript - 在打字稿中铸造道具 - React Component

Jim*_*imi 2 typescript reactjs

我正在使用带有React的typescript 2.3.4.我收到错误TS7006:参数'props'隐含有'any'类型.什么是在打字稿中投放道具的正确方法?

任何帮助表示赞赏.

interface State {
    name: string;
}

interface Props {

}


export class Profile extends React.Component<Props, State> {
    public state: State;
    public props: Props;
    constructor(props){
        super(props);
            this.state = {
               name: 'baz111'
            };
    }

    public render() {
        return (
            <section>
             <section>
                 <h3>profile 1</h3>
                 <div>baz</div>
             </section>
                <section>
                    <h3>profile 2</h3>
                    <div>{this.state.name}</div>
                </section>
            </section>
        )

    }
}
Run Code Online (Sandbox Code Playgroud)

Waz*_*ner 6

您收到此错误,因为构造函数的参数没有类型注释.它应该是:

constructor(props: Props) {
    super(props);
    this.state = {
       name: 'baz111'
    };
}
Run Code Online (Sandbox Code Playgroud)

当函数参数没有类型注释时,它将隐式地键入any.如果noImplicitAny启用了tsconfig.json文件中的选项,则在发生此类情况(您的情况)时将导致错误.

另一方面,您不必重新声明状态和道具字段,您可以将它们排除在外.