declaring a property in constructor with typescript react

后端 未结 3 1335
北恋
北恋 2021-02-12 13:22

From the draft-js documention, one can (in vanilla React, with no typescript) setup the Draft-js environment thus, noticing that the onChange property can be declar

3条回答
  •  既然无缘
    2021-02-12 14:20

    Try this:

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

    I haven't tested it, but I think it should work.


    Edit

    Yeah, there's a problem there that I haven't noticed, it should be:

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

    The type assertion (as MainState) is needed if the todos property isn't optional, if it is optional (todos?: any[]) then there's no need for the assertion.

    As for what seems to be duplication with the onChange definition, it is explained in short in the Mixins part of the typescript docs, but in your example the definition in the class:

    onChange: (state: MainState) => void;
    

    let's the compiler know that instances of Main have this method called onChange that receives a MainState and returns void.
    But the implementation of this method is only assigned when the instance is created in the ctor:

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

    If the definition is missing then the assignment in the ctor will produce a compilation error: property 'onChange' does not exist on type 'Main'.

提交回复
热议问题