首页 > 解决方案 > 在 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;

标签: javascriptreactjstypescript

解决方案


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

React.Component<P,S>

为它定义一个接口:

interface ControlBarState {
    inputValue?: string
}

然后将您的类声明为:

class ControlBar extends React.Component<YourPropsType, ControlBarState> 

推荐阅读