declaring a property in constructor with typescript react
从draft-js文档中,可以(在Vanilla React中,没有typescript)设置Draft-js环境,从而注意到
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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'。
1 2 3 4 5 6 7 | class Main extends React.Component<MainProps, MainState> { constructor(props) { super(props); this.state = { todos: [], editorState: EditorState.createEmpty() }; this.onChange = (editorState) => this.setState({ editorState }); } |
我还尝试将
1 2 3 4 | interface MainProps { model: Model; onChange: Function; } |
在typescript / react中声明这种函数属性的适当方法是什么?
尝试一下:
1 2 3 4 5 6 7 8 9 10 | 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; } |
我还没有测试过,但是我认为它应该可以工作。
编辑
是的,有一个我没有注意到的问题,应该是:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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; } |
如果
关于与
1 | onChange: (state: MainState) => void; |
让编译器知道
但是,仅当在ctor中创建实例时才分配此方法的实现:
1 | this.onChange = (editorState) => this.setState({ editorState }); |
如果缺少定义,则ctor中的赋值将产生编译错误:
您可以使用如下所示的handleChange方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { Editor, EditorState } from 'draft-js'; interface MyEditorProps { } class MyEditor extends React.Component<MyEditorProps, any> { constructor(props: MyEditorProps) { super(props); this.state = { editorState: EditorState.createEmpty() }; } handleChange(e: EditorState) { this.setState({ editorState: e }); } render() { return ( <Editor editorState={this.state.editorState} onChange={e => this.handleChange(e)} /> ); } } ReactDOM.render( <MyEditor />, document.getElementById('editor'), ); export { MyEditor } |
或者,您也可以这样尝试:
就在类的主体中,您可以在其中定义其他类的属性。我不知道,您正在运行哪个版本,但是此代码完全可以在
中使用