关于reactjs:类型’Readonly <{}>‘不存在属性’value’

Property 'value' does not exist on type 'Readonly<{}>'

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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>
    );
  }
}

我收到以下错误:

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

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

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


Component的定义如下:

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

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

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

要么:

1
2
3
4
5
type MyProps = { ... };
type MyState = { value: string };
class App extends React.Component<MyProps, MyState> {
    ...
}


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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);
  ...
};

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


问题是您尚未声明接口状态
用您合适的变量类型的"值"替换任何一个

这是一个很好的参考

1
2
3
4
5
6
7
8
9
10
11
interface AppProps {
   //code related to your props goes here
}

interface AppState {
   value: any
}

class App extends React.Component<AppProps, AppState> {
  // ...
}

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

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

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