如何在React中区分不同的表单输入?

时间:2016-11-09 09:52:39

标签: javascript html forms reactjs ecmascript-6

我有两个表单输入,我想要名字和电子邮件。

enter image description here

我遵循React文档(https://facebook.github.io/react/docs/forms.html)中的示例,但我不确定如何区分这两种不同的形式。当我输入第一个或第二个表单时,另一个表单也会收到this.state.value

constructor(props) {
    super(props);
    this.state = {
        value: '',
    }
}

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

input() {
    return (
        <form>
            <input type="text" value={this.state.value} onChange={this.handleChange.bind(this)}/>
            <input type="email" value={this.state.value} onChange={this.handleChange.bind(this)}/>
        </form>
    )
}

我正在使用ES6。我是否需要某种id来区分这两种形式?我试图在构造函数中使用不同的值(即email = ''),但它产生了相同的结果。

3 个答案:

答案 0 :(得分:2)

为每个id使用<input/>,并将其保存在state中,使用id作为key,输入值作为value {1}}。

<强> [更新]

正如下面的评论所述,我已经添加了为每个实例生成唯一id的功能。

希望这有帮助!

&#13;
&#13;
class App extends React.Component{
  constructor(props) {
      super(props);
      this.ids = {
        textInput: Math.random().toString(36).slice(-5),
        emailInput: Math.random().toString(36).slice(-5),
      }
      this.state = {}
  }

  handleChange(e) {
      this.setState({
          [e.target.id]: e.target.value,
      })
  }

  input() {
      return (
          <form>
              <input type="text" value={this.state[this.ids.textInput]} id={this.ids.textInput} onChange={this.handleChange.bind(this)}/>
              <input type="email" value={this.state[this.ids.emailInput]} id={this.ids.emailInput} onChange={this.handleChange.bind(this)}/>
          </form>
      )
  }
  
  render(){
    console.log(this.state)
    return this.input()
  }
}

ReactDOM.render(<App/>, document.getElementById('app'))
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

constructor(props) {
  super(props);
  this.state = {
    textValue: '',
    emailValue: ''
  }
}

handleTextChange(e) {
  this.setState({
    textValue: e.target.value
  })
}

handleEmailChange(e) {
  this.setState({
    emailValue: e.target.value
  })
}

input() {
  return (
    <form>
      <input type="text" value={this.state.textValue} onChange={this.handleTextChange.bind(this)}/>
      <input type="email" value={this.state.emailValue} onChange={this.handleEmailChange.bind(this)}/>
    </form>
  )
}

答案 2 :(得分:2)

你应该存储电子邮件&amp;在不同的州中的价值。

this.state = {
    text: '',
    email: ''
}

你应该改变一下handleChange方法

handleChange(e) {
  this.setState({
    [e.target.type]: e.target.value,
  })
}

希望它能帮到你