Mac*_* S. 17 javascript typescript reactjs
我是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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
错误说:"[ts]属性'playOrPause'在'ReadOnly <{}>'类型中不存在.
我试图将playOrPause属性声明为一种字符串,但它不起作用.我在这里错过了什么才能让它发挥作用?
小智 51
如果有人想知道如何在带有钩子的功能组件中实现它(而不是在类中):
const [value, setValue] = useState<number>(0);
Run Code Online (Sandbox Code Playgroud)
useState 是一个泛型函数,这意味着它可以接受类型参数。这个类型参数将告诉 TypeScript 哪些类型可以接受该状态。
fel*_*osh 35
您需要声明您的组件正在使用Statecript接口,它由Typescript的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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17176 次 |
| 最近记录: |