类型“ Readonly <{}>”上不存在属性“值”

reactjs React.js

米亚凯

2020-03-11

我需要创建一个表单,该表单将根据API的返回值显示某些内容。我正在使用以下代码:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value); //error here
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} /> // error here
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

我收到以下错误:

error TS2339: Property 'value' does not exist on type 'Readonly<{}>'.

我在代码注释的两行中都收到此错误。该代码甚至不是我的代码,我是从react官方网站(https://reactjs.org/docs/forms.html)上获得的,但是在这里不起作用。

我正在使用create-react-app工具。

第828篇《类型“ Readonly <{}>”上不存在属性“值”》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
A小卤蛋Pro 2020.03.11

Component 定义如下:

interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }

表示状态(和道具)的默认类型为:{}
如果您希望组件value处于状态,则需要这样定义它:

class App extends React.Component<{}, { value: string }> {
    ...
}

要么:

type MyProps = { ... };
type MyState = { value: string };
class App extends React.Component<MyProps, MyState> {
    ...
}
Green小宇宙伽罗 2020.03.11

event.targetEventTarget不总是有值的类型。如果是DOM元素,则需要将其转换为正确的类型:

handleChange(event) {
    this.setState({value: (event.target as HTMLInputElement).value});
}

尽管显式可能会更好,但这也会推断出状态变量的“正确”类型

古一泡芙猴子 2020.03.11

除了@ nitzan-tomer的答案,您还可以选择使用inferfaces

interface MyProps {
  ...
}

interface MyState {
  value: string
}

class App extends React.Component<MyProps, MyState> {
  ...
}

// Or with hooks, something like

const App = ({}: MyProps) => {
  const [value, setValue] = useState<string>(null);
  ...
};

只要您保持一致,就可以。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android