javascript - 在 react ts 组件中声明常量时出错
问题描述
我试图将我在网上找到的用 React JS 编写的搜索栏 css 控件转换为 React TS,但对 TS 来说有点陌生,并且很难知道要搜索什么并找出最后一个问题行有什么问题。
错误const { inputValue } = this.state;
在线,消息是
类型“Readonly<{}>”没有属性“inputValue”,也没有字符串索引签名。
我的控制代码
import * as React from 'react';
import './App.css';
class ControlBar extends React.Component {
constructor(props: any) {
super(props);
this.state = {
inputValue: ''
};
this.onInputChange = this.onInputChange.bind(this);
}
onInputChange(e: any) {
const { value } = e.target;
this.setState({
inputValue: value
});
}
public render() {
const { inputValue } = this.state;
return (<div className='input-wrapper'>
<input
placeholder='Search...'
value={inputValue}
spellCheck={false}
/>
<span className='input-highlight'>
{ inputValue.replace(/ /g, "\u00a0") }
</span>
</div>);
}
}
export default ControlBar;
解决方案
您可以在S
的签名部分定义状态的类型React.Component
:
React.Component<P,S>
为它定义一个接口:
interface ControlBarState {
inputValue?: string
}
然后将您的类声明为:
class ControlBar extends React.Component<YourPropsType, ControlBarState>
推荐阅读
- javascript - NS_ERROR_XPC_SECURITY_MANAGER_VETO 发生在 Ajax 和 Django 中
- javascript - 在 HTML 表单中包含 jQuery 函数
- objective-c - 在 Mojave 上使用 Core Animation 图层绘图时如何解决透明系统颜色问题?
- laravel - Laravel 广播到私人频道失败
- react-native - React Native Navigation - 在 React Native v0.59 上运行 npm 运行 android 构建错误
- java - 如何在包含句子的字符串数组中搜索确切的单词(JAVA)
- java - JUnit Mockito 测试:零交互
- c# - 创建泛型类c#的实例
- python-3.x - 参考如何在 python 整数与列表中工作?在列表中两个值都相同,为什么整数部分中的值不是 2?
- c - 使用循环打印数组会给出垃圾值,但单独打印会给出正确的值