【问题标题】:How to get the value of two input fields at same time in React?如何在 React 中同时获取两个输入字段的值?
【发布时间】:2020-03-29 21:51:34
【问题描述】:

这是表单,我想在用户提交表单时获取姓名和年龄的值。

<form>
    <input type='text' name='name'></input>
    <input type='number' name='age'></input>
   <input type='submit' />
</form>

【问题讨论】:

  • 你读过 ReactJS 的文档吗?至少首页介绍?这涉及获取单个字段的值,然后您可以推断为两个。

标签: reactjs react-native react-redux


【解决方案1】:

受控组件(React方式)

您可以将两个值都存储在状态中。 然后在表单的onSubmit 中使用它们。

https://reactjs.org/docs/forms.html

/* component init */
constructor(props) {
  super(props);
  this.state = {
    value1: '',
    value2: ''
  }
}
/* handle changes */
onChange1(event) {
  this.setState({ value1: event.target.value });
}

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

/* submit method */
  onSubmit(event) { 
    event.preventDefault(); 
    const value1 = this.state.value1;
    const value2 = this.state.value2;
    console.log(value1, value2);
  }

/* render */
<form onSubmit={this.onSubmit}> 
   <input type="text" value={this.state.value1} onChange={this.onChange1} /> 
   <input type="number" value={this.state.value2} onChange={this.onChange2} /> 
   <input type="submit" value="Submit" />
 </form>

不受控制的组件(不是 React 方式)

如果你想使用不受控制的组件(不要存储值 yourswlf)你必须使用refs

更多关于参考https://reactjs.org/docs/refs-and-the-dom.html

/* component init */
constructor(props) {
  super(props);
  this.input1 = React.createRef(); 
  this.input2 = React.createRef(); 
}

/* submit method */
  handleSubmit(event) { 
    event.preventDefault(); 
    const value1 = this.input1.current.value;
    const value2 = this.input2.current.value;
    console.log(value1, value2);
  }

/* render */
<form onSubmit={this.handleSubmit}> 
   <input type="text" ref={this.input1} /> 
   <input type="number" ref={this.input2} /> 
   <input type="submit" value="Submit" />
 </form>

【讨论】:

  • 我可以不使用状态吗
  • 查看不受控制的组件主题:)
  • 我在控制台日志中收到错误“无法读取 null 的属性‘值’”
  • 让我们尝试将 createRef 从 componentDidMount 移动到 constructor
  • 你可以在没有状态的情况下这样做,但这在 React 中既不是必需的也不是首选。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多