从 Draft-js 文档中,可以(在原版 React 中,没有typescript)设置 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} />;
}
}
但是,当我尝试对 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
属性添加到props中
interface MainProps {
model: Model;
onChange: Function;
}
在typescript/react中声明这样的函数属性的合适方法是什么?