【问题标题】:React State value call反应状态值调用
【发布时间】:2021-03-30 23:18:24
【问题描述】:

我想创建一个表单并保存一些值。 我有这个构造函数代码:

  constructor(props) {
super(props);
this.state = {value: ''};

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

并具有handleChange功能:

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

并具有handleSubmit功能:

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

handleSubmit 函数有错误:

类型“{}”.ts(2339) 上不存在属性“值”。

如何解决?

这里是完整的代码:

class NameForm 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);
    event.preventDefault();
  }

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

这是错误

【问题讨论】:

  • 把整个代码放在这里
  • @praga2050 完成
  • 我在这里没有看到任何问题 stackblitz.com/edit/react-ie2rt6 看到这个 stackblitz
  • @praga2050 我已附上错误照片
  • 看起来更像是 IDE 问题。您是否尝试运行 yarn start 或 npm start 并查看此错误是否出现在浏览器中。

标签: reactjs web bootstrap-4 frontend


【解决方案1】:

由于您使用的是打字稿,因此您需要做这样的事情。看看这个 stackBlitz

https://stackblitz.com/edit/react-ts-gfcdog

import React from "react";

interface State{
  value? : string
}

export default class NameForm extends React.Component<{},State> {
  constructor(props: any) {
    super(props);
    this.state = { value: "" };

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

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

  handleSubmit(event: any) {
    alert("A name was submitted: " + this.state.value);
    event.preventDefault();
  }

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

【讨论】:

    猜你喜欢
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2019-02-27
    • 2017-10-20
    相关资源
    最近更新 更多