gpt4 book ai didi

javascript - 在 react ts 组件中声明常量时出错

转载 作者:行者123 更新时间:2023-11-30 20:29:23 25 4
gpt4 key购买 nike

我试图将我在网上找到的一个用 React JS 编写的搜索栏 css 控件转换为 React TS,但我对 TS 有点陌生,并且很难知道要搜索什么并找出最后一个有什么问题问题行。

错误在 const { inputValue } = this.state; 行,消息是

Type 'Readonly<{}>' has no property 'inputValue' and no string index signature.

我的控制代码

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;

最佳答案

你可以在React.Component的签名的S部分定义状态的类型:

React.Component<P,S>

为它定义一个接口(interface):

interface ControlBarState {
inputValue?: string
}

然后将您的类声明为:

class ControlBar extends React.Component<YourPropsType, ControlBarState> 

关于javascript - 在 react ts 组件中声明常量时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50525678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com