使用 typescript react 在构造函数中声明一个属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37302382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:29:45  来源:igfitidea点击:

declaring a property in constructor with typescript react

reactjstypescript

提问by Leahcim

From the draft-js documention, one can (in vanilla React, with no typescript) setup the Draft-js environment thus, noticing that the onChangeproperty can be declared directly in the constructor:

从 Draft-js 文档中,可以(在原版 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} />;
  }
}

However, when I try to do the same with Typescript/React (code below), I get this error

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

error TS2339: Property 'onChange' does not exist on type 'Main'.

错误 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 });
  }

I also tried adding onChangeas a property to the props

我也尝试将onChange属性添加到道具中

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

What is the appropriate way to declare such a function property in typescript/react?

在打字稿/反应中声明这样的函数属性的合适方法是什么?

采纳答案by Nitzan Tomer

Try this:

试试这个:

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;

}

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<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;

}

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

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

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

至于似乎与onChange定义重复的内容,在 typescript docsMixins 部分中对其进行了简短的解释,但在您的示例中是类中的定义:

onChange: (state: MainState) => void;

let's the compiler know that instances of Mainhave this method called onChangethat receives a MainStateand returns void.
But the implementation of this method is only assigned when the instance is created in the ctor:

让编译器知道Main调用此方法的实例onChange接收 aMainState并返回void
但是这个方法的实现只有在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'.

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

回答by Karim Ben Yezza

You can use handleChange method like this :

您可以像这样使用 handleChange 方法:

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 }

回答by SMSk

Alternatively, you can try it like this:

或者,您可以像这样尝试:

private onChange = (editorState) => this.setState({ editorState } as MainState)

private onChange = (editorState) => this.setState({ editorState } as MainState)

just in the body of the class, where you define other class properties. I dunno, which version you're running, but this code totally works in ES2015and TypeScript 2.0.10

只是在类的主体中,您可以在其中定义其他类属性。我不知道你在运行哪个版本,但这段代码完全适用于ES2015TypeScript2.0.10