簡體   English   中英

如何更改 state 以響應表單

[英]How to change the state in react with a form

我有一個應該更新初始 state 的表單,我遵循了許多教程,我的代碼看起來與它們相同,但由於某種原因它沒有更新 state。

import React, { Component } from 'react';

class Create extends Component{
   constructor(props){
      super(props);

      this.state = {
         title: "",
         body: "",
         error: ""
      } 
   }

   onTitleChange(e) {
      const title = e.target.value;
      this.setState({title})
   }

   onBodyChange(e) {
      const body = e.target.value;
      this.setState({body})
   }

   onSubmit(e) {
      e.preventDefault();

      if(!this.state.title || !this.state.body){
         this.setState(() => ({ error: "Please fill in all gaps"}))
      } else {
         this.setState(() => ({ error: "" }))
         // Send info to the main page
         alert(this.state.title);
      }
   }

   render(){
      return(
         <div>
         {this.state.error && <p>{this.state.error}</p>}
         <form onSubmit = {this.onSubmit}>
         <label>Put a title for your note</label>
         <input 
            placeholder="Title"
            type="text"
            value={this.state.title}
            autoFocus
            onChange= {this.onTitleChange}
         />
         <label>Write your note</label>
         <textarea 
            placeholder="Note"
            value={this.state.body}
            autoFocus
            onChange = {this.onBodyChange}
         />
         <input type="submit" value="Submit"/>
         </form>
         </div>
      );
   }
}

export default Create;

當我在 React 開發人員工具中檢查當前的 state 時,它顯示 state 保持不變,我不知道為什么,因為日志中沒有錯誤。 我正在使用 webpack,babel 並做出反應。

///////////////// 已編輯 /////////////////

我按照你們給我的建議編輯了我的代碼,但它仍然不起作用。 提交表單時應該會出現一個警報,但也不會被觸發,所以我相信沒有任何函數被觸發。

這是我編輯的代碼:

import React, { Component } from 'react';

class Create extends Component{
   constructor(props){
      super(props);
      this.onTitleChange = this.onTitleChange.bind(this);
      this.onBodyChange = this.onBodyChange.bind(this);
      this.onSubmit = this.onSubmit.bind(this);

      this.state = {
         title: "",
         body: "",
         error: ""
      } 
   }

   onTitleChange(e) {
      const title = e.target.value;
      this.setState((prevState) => {
         return {
           ...prevState,
           title
         };
       });
   }

   onBodyChange(e) {
      const body = e.target.value;
      this.setState((prevState) => {
         return {
           ...prevState,
           body
         };
       });
   }

   onSubmit(e) {
      e.preventDefault();

      if(!this.state.title || !this.state.body){
         this.setState((prevState) => {
            return {
              ...prevState,
              error: "Please fill in all gaps"
            };
          });
      } else {
         this.setState((prevState) => {
            return {
              ...prevState,
              error: ""
            };
          });
         // Send info to the main page
         alert(this.state.title);
      }
   }

   render(){
      return(
         <div>
         {this.state.error && <p>{this.state.error}</p>}
         <form onSubmit = {this.onSubmit}>
         <label>Put a title for your note</label>
         <input 
            placeholder="Title"
            type="text"
            value={this.state.title}
            autoFocus
            onChange= {this.onTitleChange}
         />
         <label>Write your note</label>
         <textarea 
            placeholder="Note"
            value={this.state.body}
            autoFocus
            onChange = {this.onBodyChange}
         />
         <input type="submit" value="Submit"/>
         </form>
         </div>
      );
   }
}

export default Create;

React 的setState()接受 object,而不是 function。 因此,將您的onSubmit()更改為:

if(!this.state.title || !this.state.body){
    this.setState({ error: "Please fill in all gaps"})
} else {
    this.setState({ error: "" })
    // Send info to the main page
    alert(this.state.title);
}

最好使用以前的 state 並且只更新所需的(輸入值)值。

在你的情況下,你正在用標題替換現有的 state (整個對象),body onBodyChange

 onTitleChange () {
    const title = e.target.value;
    this.setState((prevState) => {
      return {
        ...prevState,
        title
      };
    });
  };
<

您應該嘗試在構造函數中綁定事件處理程序,因為這些事件處理函數中的this似乎是未定義的。 React 文檔概述了為什么需要綁定,這里是另一個有用的頁面,關於在 React 中處理 forms

 constructor(props) { super(props); ... this.onTitleChange = this.onTitleChange.bind(this); this.onBodyChange = this.onBodyChange.bind(this); this.onSubmitChange = this.onSubmitChange.bind(this); }

在構造函數中綁定的另一種方法是使用箭頭函數來隱式綁定this的事件處理程序。

 class Create extends Component {... onTitleChange = () => {... } onBodyChange = () => {... } onSubmitChange = () => {... } }

編輯:由於我的聲譽太低,無法對您的帖子發表評論,但您剛剛所做的更改似乎有錯字。

this.onSubmitC = this.onSubmit.bind(this)應該改為

this.onSubmit = this.onSubmit.bind(this)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM