声明构造函数中的属性与typescript反应

Lea*_*cim 12 typescript reactjs

从draft-js文档中,可以(在vanilla React中,没有打字稿)设置Draft-js环境,注意到onChange属性可以直接在构造函数中声明:

import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';

class MyEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = (editorState) => this.setState({editorState});
  }
  render() {
    const {editorState} = this.state;
    return <Editor editorState={editorState} onChange={this.onChange} />;
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用Typescript/React(下面的代码)执行相同操作时,我收到此错误

错误TS2339:属性'onChange'在'Main'类型上不存在.

class Main extends React.Component<MainProps, MainState> {

    constructor(props) {
    super(props);
    this.state = { todos: [], editorState: EditorState.createEmpty() };
    this.onChange = (editorState) => this.setState({ editorState });
  }
Run Code Online (Sandbox Code Playgroud)

我也尝试添加onChange作为道具的属性

interface MainProps {
    model: Model;
    onChange: Function;
}
Run Code Online (Sandbox Code Playgroud)

在typescript/react中声明这样的函数属性的适当方法是什么?

Nit*_*mer 9

试试这个:

class Main extends React.Component<MainProps, MainState> {
    constructor(props) {
        super(props);
        this.state = { todos: [], editorState: EditorState.createEmpty() };
        this.onChange = (editorState) => this.setState({ editorState });
    }

    onChange: (state: MainState) => void;

}
Run Code Online (Sandbox Code Playgroud)

我没有测试它,但我认为它应该工作.


编辑

是的,那里有一个我没注意到的问题,应该是:

class Main extends React.Component<MainProps, MainState> {
    constructor(props) {
        super(props);

        this.state = { todos: [], editorState: EditorState.createEmpty() };
        this.onChange = (editorState) => this.setState({
            editorState: editorState
        } as MainState);
    }

    onChange: (state: MainState) => void;

}
Run Code Online (Sandbox Code Playgroud)

类型的断言(as MainState需要)如果todos(属性是不可选的,如果它是可选的todos?: any[]),那么就没有必要断言.

至于什么似乎与onChange定义重复,它在typescript文档Mixins部分简要解释,但在您的示例中类中的定义:

onChange: (state: MainState) => void;
Run Code Online (Sandbox Code Playgroud)

让编译器知道Main调用此方法的实例onChange接收MainState并返回void.
但是只有在ctor中创建实例时才会分配此方法的实现:

this.onChange = (editorState) => this.setState({ editorState });
Run Code Online (Sandbox Code Playgroud)

如果缺少定义,那么ctor中的赋值将产生编译错误:property 'onChange' does not exist on type 'Main'.