【问题标题】:Resetting dropdown box to original value in react在反应中将下拉框重置为原始值
【发布时间】:2021-11-09 21:16:49
【问题描述】:

您好,我正在使用 react 并且对它相当陌生,我正在努力在用户提交运动员后(单击创建记录按钮后)将字段值重置为其原始状态,并且我想要下拉文本框如果用户已将字段更改为其他内容,则返回“其他”。举个例子。 名字:“约翰”, 姓氏:“史密斯”, 运动:“男子高尔夫”将重置为

名字:“”, 姓: ””, 运动:“其他” 我设法重置了所有其他字段,但运动下拉字段没有重置,我不知道为什么。这是我正在使用的代码。

import React from "react";
import "./athleteEntryStyle.css";
import { baseUrl } from "../../serviceConfig";

interface Props {
  username?: string;
  password?: string;
  dominant_foot?: string;
  preferred_name?: string;
  position?: string;
  firstName: string;
  middleName: string;
  lastName: string;
  phone: string;
  email: string;
  dateOfBirth: string;
  sport: string;
}

interface State {
  username?: string;
  password?: string;
  dominant_foot?: string;
  preferred_name?: string;
  position?: string;
  firstName: string;
  middleName: string;
  lastName: string;
  phone: string;
  email: string;
  dateOfBirth: string;
  sport: string;
}

export class AthleteEntry extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
      username: props.username,
      password: props.password,
      dominant_foot: props.dominant_foot,
      preferred_name: props.preferred_name,
      position: props.position,
      firstName: props.firstName,
      middleName: props.middleName,
      lastName: props.lastName,
      phone: props.phone,
      email: props.email,
      dateOfBirth: props.dateOfBirth,
      sport: props.sport,
    };

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

  handleChange(event: { target: any }) {
    const target = event.target;
    const value = target.value;
    const name = target.name;
    console.log(target);
    console.log(value);
    console.log(name);
    const newState = { [name]: value } as Pick<Props, keyof State>;
    this.setState(newState);
    
  }

  handleSubmit(event: { preventDefault: () => void }) {
    const request = JSON.stringify({
      username: this.state.username,
      email: this.state.email,
      password: this.state.password,
      first_name: this.state.firstName,
      middle_name: this.state.middleName,
      last_name: this.state.lastName,
      phone_number: this.state.phone?.toString(),
      dominant_foot: this.state.dominant_foot,
      sport: this.state.sport,
      position: this.state.position,
      preferred_name: this.state.preferred_name,
      date_of_birth: new Date(this.state.dateOfBirth).toISOString(),
    });

    console.log("Request from app");
    console.log(request);

    const requestOptions = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: request,
    };
    this.setState({firstName: "", middleName: "", lastName: "", preferred_name: "", dateOfBirth: "date", phone: "", email: "", 
    username: "", password: "", dominant_foot: "", sport: "Other", position: "" });
    //NOTE: This is assuming your service instance is running locally, we have to either make a config file that allows you to switch this as necessary or
    //switch this to the hosted service when that becomes a thing
    fetch(baseUrl + "athlete/create", requestOptions).then(function (response) {
      if (response.status == 201) {
        alert("An athlete was successfully created.");
      } else {
        alert(
          "Error creating athlete: API responded with code " +
            response.status.toString()
        );
      }
    });
    event.preventDefault();

  }

  render() {
    return (
      <form
        className="form"
        onSubmit={this.handleSubmit}
        style={{
          display: "flex",
          padding: "20px",
          height: "100vh",
          background: "linear-gradient(#fff, #d00000)",
        }}
      >
        <div>
          <div style={styles}>
            <label className="label">First Name:</label>
            <input
              name="firstName"
              className="input"
              type="text"
              value={this.state.firstName}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Middle Name:</label>
            <input
              name="middleName"
              className="input"
              type="text"
              value={this.state.middleName}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Last Name:</label>
            <input
              name="lastName"
              className="input"
              type="text"
              value={this.state.lastName}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Preferred Name:</label>
            <input
              name="preferred_name"
              className="input"
              type="text"
              value={this.state.preferred_name}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Date of Birth:</label>
            <input
              name="dateOfBirth"
              className="input"
              type="date"
              value={this.state.dateOfBirth}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Phone Number:</label>
            <input
              name="phone"
              className="input"
              type="text"
              value={this.state.phone}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Email:</label>
            <input
              name="email"
              className="input"
              type="text"
              value={this.state.email}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Username:</label>
            <input
              name="username"
              className="input"
              type="text"
              value={this.state.username}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Password:</label>
            <input
              name="password"
              className="input"
              type="password"
              value={this.state.password}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Dominant Foot:</label>
            <input
              name="dominant_foot"
              className="input"
              type="text"
              value={this.state.dominant_foot}
              onChange={this.handleChange}
            />
          </div>
          <div style={styles}>
            <label className="label">Sport:</label>
            {/* <input
              name="sport"
              className="input"
              type="text"
              value={this.state.sport}
              onChange={this.handleChange}
            /> */}
            <select
              name="sport"
              className="input"
              id="sport"
              defaultValue="Other"
              onChange={this.handleChange}
            >
              <option value="Football (MFB)">Football (MFB)</option>
              <option value="Baseball (MBA)">Baseball (MBA)</option>
              <option value="Softball (WSB)">Softball (WSB)</option>
              <option value="Men's Basketball (MBB)">
                Men's Basketball (MBB)
              </option>
              <option value="Women's Basketball (WBB)">
                Women's Basketball (WBB)
              </option>
              <option value="Men's Cross Country (MCC)">
                Men's Cross Country (MCC)
              </option>
              <option value="Women's Cross Country (WCC)">
                Women's Cross Country (WCC)
              </option>
              <option value="Men's Golf (MGO)">Men's Golf (MGO)</option>
              <option value="Women's Golf (WGO)">Women's Golf (WGO)</option>
              <option value="Women's Soccer (WSO)">Women's Soccer (WSO)</option>
              <option value="Women's Volleyball (WVB)">
                Women's Volleyball (WVB)
              </option>
              <option value="Women’s Bowling (WBW)">
                Women’s Bowling (WBW)
              </option>
              <option value="Men’s Gymnastics (MGY)">
                Men’s Gymnastics (MGY)
              </option>
              <option value="Women’s Gymnastics (WGY)">
                Women’s Gymnastics (WGY)
              </option>
              <option value="Women’s Swimming/Diving (WSW)">
                Women’s Swimming/Diving (WSW)
              </option>
              <option value="Men’s Tennis (MTE)">Men’s Tennis (MTE)</option>
              <option value="Women’s Tennis (WTE)">Women’s Tennis (WTE)</option>
              <option value="Men’s Wrestling (MWR)">
                Men’s Wrestling (MWR)
              </option>
              <option value="Women’s Rifle (WRI)">Women’s Rifle (WRI)</option>
              <option value="Women’s Track (WTO)">Women’s Track (WTO)</option>
              <option value="Men’s Track (MTO)">Men’s Track (MTO)</option>
              <option value="Other">Other</option>
            </select>
          </div>
          <div style={styles}>
            <label className="label">Position:</label>
            <input
              name="position"
              className="input"
              type="text"
              value={this.state.position}
              onChange={this.handleChange}
            />
          </div>
          <div style={{ marginBottom: 12, padding: 10 }}>
            <label>
              <input type="submit" value="Create Record" className="button"/>
            </label>
          </div>
        </div>
      </form>
    );
  }
}
const styles = {
  marginBottom: 12,
};

上面的大部分代码对您来说都无关紧要,除了进行更改的那一行。所以

this.setState({firstName: "", middleName: "", lastName: "", preferred_name: "", dateOfBirth: "date", phone: "", email: "", 
    username: "", password: "", dominant_foot: "", sport: "Other", position: "" });

是进行更改的地方。

【问题讨论】:

  • 你快到了。只需在此块中设置您想要的状态if (response.status == 201) { ... }

标签: javascript reactjs dropdown


【解决方案1】:

看起来你在你的select 组件中有defaultValue="Other" 作为道具,但你真正想要的是value={this.state.sport},就像你在上面注释掉的input 中一样。这将使它成为一个受控组件,因此该选择字段的值将基于您的状态。其他字段都是这样完成的,看起来可能只是一个疏忽。

【讨论】:

  • 另外,作为旁注,我们通常不希望从传递给它的 props 中获取组件的状态。通常解决这个问题只需要对组件进行一点重构/思考就有点不同。这是 React 团队关于派生状态的有用博客文章 reactjs.org/blog/2018/06/07/…
  • 在尝试后它可以工作,但我需要在最初加载页面时将 defaultValue 设置为 Option。当它设置为 value={this.state.sport} 时,第一个选项是 Football 首先出现。即使同时使用 defaultValue 和 value 之类的东西, value 似乎也会覆盖 defaultValue
  • 在构造函数中设置初始状态时尝试this.state = { // everything else sport: "Other", };
  • 这是派生状态问题的一部分,为了快速修复,我会说确保您将 sport 属性传递为 "Other",但从长远来看,它会更好重构,因此状态不基于传递给组件的道具
猜你喜欢
  • 2015-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多