小编典典

使用状态与TypeScript反应

reactjs

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

看一看最重要的代码:

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 <{}>类型上不存在。

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


阅读 252

收藏
2020-07-22

共1个答案

小编典典

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

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>
    );
  }
}
2020-07-22