使用状态与 TypeScript 进行响应

我刚接触打字机。我在渲染方法中显示 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] Property 'playOrPause' does not exist on type 'ReadOnly<{}>'.

我尝试将 playOrPuse 属性声明为一种字符串类型,但是它不起作用。

我到底错过了什么?

139919 次浏览

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

In my case ( working with TypeScript, and the state value was actually a boolean ) I've had the same problem, I've fixed it by passing the state value I wanted to mark as output to String():

import React, { Component } from 'react';


interface ITestProps {
name: string;
}


interface ITestState {
toggle: boolean;
}


class Test extends Component<ITestProps, ITestState> {
constructor(props: ITestProps) {
super(props);


this.state = {
toggle: false,
};


this.onClick = this.onClick.bind(this);
}


onClick() {
this.setState((previousState, props) => ({
toggle: !previousState.toggle,
}));
}


render() {
return (
<div>
Hello, {this.props.name}!
<br />
Toggle state is: {String(this.state.toggle)}
</div>
)
}
}

In case anyone is wondering how to implement it in functional components with hooks ( not in a class):

const [value, setValue] = useState<number>(0);

useState is a generic function, that means that it can accept a type parameter. This type-parameter will tell TypeScript which types are acceptable for this state.