小编典典

在带有TypeScript的构造函数中声明属性

reactjs

从草稿js文档中,可以(在普通React中,没有打字稿)设置草稿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} />;
  }
}

但是,当我尝试对Typescript / React(以下代码)执行相同操作时,出现此错误

错误TS2339:类型’Main’上不存在属性’onChange’。

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

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

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

interface MainProps {
    model: Model;
    onChange: Function;
}

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


阅读 981

收藏
2020-07-22

共1个答案

小编典典

试试这个:

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;

}

我还没有测试过,但是我认为它应该可以工作。


编辑

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

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;

}

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

至于似乎与onChange定义重复的内容,将在typescript
docs
Mixins部分中简要说明,但在您的示例中,该类中的定义:

onChange: (state: MainState) => void;

让编译器知道的实例Main具有此方法的实例,该方法onChange接收a MainState并返回void
但是,仅在ctor中创建实例时才分配此方法的实现:

this.onChange = (editorState) => this.setState({ editorState });

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

2020-07-22