从下拉列表和输入中获取值

时间:2017-03-03 23:56:12

标签: reactjs

我试图从所有输入中获取值。我可以从输入中获取输入值,但不能从选择标记的下拉列表中获取输入值。

我做错了什么?

class App extends Component {
  constructor(props){
    super(props)

    this.state = {
      contacts
    };
  }

  removeContact(id) {
     const removedID = contact => contact.id !== id;
     const updatedContacts = this.state.contacts.filter(removedID)
     this.setState({contacts: updatedContacts})
  }

   handleSubmit(e){
     e.preventDefault(e)
     const target = e.target;
     console.log(target.email.value)
     console.log(target.gender.value)

   }


  render() {
    return (
      <div className="App">
            <form onSubmit={this.handleSubmit}>
            <div>
              <label>
               First Name:
                 <input type="text" value={this.state.first_name} name="first_name" />
              </label>
            </div>
            <div>
              <label>
               Last Name:
                 <input type="text" value={this.state.last_name} name="last_name" />
              </label>
            </div>
            <div>
              <label>
               Email:
                 <input type="text" value={this.state.email} name="email"/>
              </label>
            </div>
            <div>
              <select value={this.state.gender} onChange={this.handleSubmit}> 
                  <option name="male"> Male</option>
                  <option name="female">Female</option>
              </select>
            </div>
            <input type="submit" value="Submit" />
          </form>

1 个答案:

答案 0 :(得分:2)

您将value的{​​{1}}设置为州,但在选择新值时不更改状态。一旦值发生变化,您需要select,以便它反映在DOM中:

setState
class Example extends React.Component {
  constructor() {
    super();
    this.state = { gender: "male" };
    this.handleChange = this.handleChange.bind(this);
  }

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

  render() {
    return (
      <select value={this.state.gender} onChange={this.handleChange}>
        <option name="male"> Male</option>
        <option name="female">Female</option>
      </select>
    );
  }
}

ReactDOM.render(<Example />, document.getElementById("root"));