在TypeScript中使用状态来做出反应 [英] Using state in react with TypeScript

查看:42
本文介绍了在TypeScript中使用状态来做出反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是TypeScript的新手.在render方法内部显示this.state.something或将其分配给函数内部的变量时,我遇到了问题.

I am new to TypeScript. I've got a problem with displaying this.state.something inside the render method or assigning it to a variable inside a function.

看看最重要的代码:

interface State {
    playOrPause?: string;
}

class Player extends React.Component {
    constructor() {
        super();

        this.state = {
            playOrPause: 'Play'
        };
    }

    render() {
        return(
            <div>
                <button
                    ref={playPause => this.playPause = playPause}
                    title={this.state.playOrPause} // in this line I get an error
                    >
                    Play
                </button>
           </div>
        );
    }
}

错误显示:"[ts]属性'playOrPause'在类型'ReadOnly< {}>'上不存在.

The errors says: "[ts] Property 'playOrPause' does not exist on type 'ReadOnly<{}>'.

我试图将playOrPause属性声明为字符串类型,但它不起作用.我在这里想让它起作用吗?

I tried to declare the playOrPause property to be a type of string and it didn't work. What am I missing here to make it work?

推荐答案

您需要声明您的组件正在使用Typescript的泛型使用的State接口.

You need to declare that your component is using the State interface, it used by Typescript's Generics.

interface IProps {
}

interface IState {
  playOrPause?: string;
}

class Player extends React.Component<IProps, IState> {
  // ------------------------------------------^
  constructor(props: IProps) {
    super(props);

    this.state = {
      playOrPause: 'Play'
    };
  }

  render() {
    return(
      <div>
        <button
          ref={playPause => this.playPause = playPause}
          title={this.state.playOrPause} // in this line I get an error
        >
          Play
        </button>
      </div>
    );
  }
}

这篇关于在TypeScript中使用状态来做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆