我需要创建一个表单,该表单将根据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)得到的,但它在这里不起作用。

我正在使用创建-反应-应用程序工具。


当前回答

问题是您还没有声明接口状态 将任意变量替换为value的合适变量类型

这是一个很好的参考资料

interface AppProps {
   //code related to your props goes here
}

interface AppState {
   value: any
}

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

其他回答

组件的定义如下:

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

这意味着状态(和道具)的默认类型是:{}。 如果你想让你的组件在状态中有值,那么你需要像这样定义它:

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

Or:

type MyProps = { ... };
type MyState = { value: string };
class App extends React.Component<MyProps, MyState> {
    ...
}
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>('');
  ...
};

类型也很好,就像@nitzan-tomer的回答一样,只要你是一致的。

我建议使用

仅用于字符串状态值

export default class Home extends React.Component<{}, { [key: string]: string }> { }

用于字符串键和任何类型的状态值

export default class Home extends React.Component<{}, { [key: string]: any}> { }

对于任何键/任何值

export default class Home extends React.Component<{}, { [key: any]: any}> {}

如果你不想传递接口状态或道具模型,你可以试试这个

class App extends React.Component <any, any>

问题是您还没有声明接口状态 将任意变量替换为value的合适变量类型

这是一个很好的参考资料

interface AppProps {
   //code related to your props goes here
}

interface AppState {
   value: any
}

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