【问题标题】:Input elements not updating in React输入元素在 React 中没有更新
【发布时间】:2017-10-01 07:27:09
【问题描述】:

我正在构建一个非常基本的 React 应用程序,但在表单输入方面存在一些问题: 我的状态:

class App extends Component {
    constructor(){
    super();
    this.state = {
    books: [],
    book:{
      author:"",
    title: ""
   }
  }
  this.handleInputChange = this.handleInputChange.bind(this)
 }

我的表格:

<form onSubmit={this.addBook}>
          <input
            name="author"
            type="text"
            placeholder="author"
            value={this.state.book.author}
            onChange={this.handleInputChange}
          /><br/>
          <input
            name="title"
            type="text"
            placeholder="title"
            value={this.state.book.title}
            onChange={this.handleInputChange}
          /><br/>
          <input type="submit" />
          <button>Update</button>
          <button>Delete</button>
        </form>

我的事件处理程序:

handleInputChange(event) {
    this.setState({
      [event.target.name]: event.target.value
    });
  }

我仍然无法在输入字段中输入数字。当我尝试对一个值进行数字化时,没有任何反应,并且输入字段没有正确更新。有什么建议么? 谢谢

【问题讨论】:

  • handleInputChange addBook 哪个部分不能正常工作?
  • handleInputChange

标签: javascript reactjs


【解决方案1】:

您的图书状态是 state.book.title 和 state.book.author,因此您需要在 setState 中指定它是您要使用 event.target.value 更新的 state.book 对象。

希望这能解决问题:

handleInputChange(event) {
  this.setState({
    book: {
    ...this.state.book,
    [event.target.name]: event.target.value
    },
  });
}

更新嵌套书籍对象的状态时,您需要对其进行复制,但将要更改的属性设置为新值。这就是省略号的帮助。

更多信息在这里:How do I setState for nested array?

【讨论】:

    【解决方案2】:

    title/author 属性在 book 对象中。看起来您只是引用 state.author 或 state.title,但您需要引用 state.book.title 或 state.book.author。试试这个:

    handleInputChange(event) {
        this.setState({
          book[event.target.name]: event.target.value
        });
      }
    

    【讨论】:

      猜你喜欢
      • 2019-08-30
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-29
      • 2018-10-13
      • 2022-10-12
      相关资源
      最近更新 更多