Javascript 使用状态与 TypeScript 反应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46987816/
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
Using state in react with TypeScript
提问by Maciej S.
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.
我是 TypeScript 的新手。我在渲染方法中显示 this.state.something 或将其分配给函数中的变量时遇到问题。
Have a look at the most important piece of code:
看看最重要的一段代码:
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>
);
}
}
The errors says: "[ts] Property 'playOrPause' does not exist on type 'ReadOnly<{}>'.
错误说:“[ts] 属性 'playOrPause' 在类型 'ReadOnly<{}>' 上不存在。
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?
我试图将 playOrPause 属性声明为一种字符串,但它不起作用。我在这里缺少什么才能使它工作?
回答by felixmosh
You need to declare that your component is using the State interface, it used by Typescript's Generics.
您需要声明您的组件正在使用 State 接口,它由 Typescript 的泛型使用。
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>
);
}
}

