当我输入名字标签时,它也会写在名字标签内

时间:2018-07-04 11:59:55

标签: json reactjs web-frontend

我刚刚使用提交按钮创建了一个简单的名字和姓氏标签。问题是,当我在名字标签内书写时,它也写在姓氏标签中。为什么会这样?

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import App from "./components/app";
import reducers from "./reducers";

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: "" };

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

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

  handleChanges(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>
        <label>
          LastName:
          <input
            type="text"
            value={this.state.value}
            onChange={this.handleChanges}
          />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

ReactDOM.render(<NameForm />, document.querySelector(".container"));

3 个答案:

答案 0 :(得分:1)

这是因为要将输入字段的值保存在相同的变量this.state.values中。 您应该尝试分别保存它们,this.state.firstName / this.state.lastname

答案 1 :(得分:1)

那是因为您只有一个value代表您的名字和姓氏。

您可以使用两个单独的状态变量,每个变量一个。

示例

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { firstName: "", lastName: "" };

    this.handleFirstNameChange = this.handleFirstNameChange.bind(this);
    this.handleLastNameChange = this.handleLastNameChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

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

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

  handleSubmit(event) {
    event.preventDefault();
    alert("A name was submitted: ", this.state.firstName, this.state.lastName);
  }

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

答案 2 :(得分:1)

每个输入字段必须有不同的状态变量,但对于您而言,您只是创建了值状态变量

    this.state = { value: "" };

代表每个输入标签的值。