javascript - 如何循环表单输入并在 react 中获取值

标签 javascript reactjs ecmascript-6

给出以下内容:

constructor () {

    super();
    this.state = {
        inputs : [
            { type: 'email', placeholder: 'Email Address' }
        ]
    };

}

render () {
  return {
    <div>

    {
      // Itterates over all inputs in the current state
      this.state.inputs.map((item, i) => (
        <Input key={i} id={'input-' + i} ref={'input-' + i} type={item.type} placeholder={item.placeholder} />
      ))
    }

     <button onClick={this.submit.bind(this)}>submit</button>

   </div>

  };
}

提交表单后如何获取值?例如

submit () {
  // Need to loop over inputs and get values for all of them.
}

最佳答案

我已经根据一些最佳实践重组了代码。如果您对此有任何疑问,请告诉我。

state = {
    inputs : [
        { type: 'email', placeholder: 'Email Address', id: 'email' },
        { type: 'text', placeholder: 'Your Name', id: 'name' },
    ]
},

submit = () => {
  // Need to loop over inputs and get values for all of them.
  this.state.inputs.map((input) => {
    const node = ReactDOM.findDOMNode(this.refs[input.id]);
    // do what you want to do with `node`
  })
},

renderInput = (input) => {
  // element index as key or reference is a horrible idea
  // for example if a new input is unshifted it will have the same 
  // reference or key, which will render the idea of key, reference invalid

  return (
    <Input 
      id={input.id} 
      key={input.id} 
      ref={input.id} 
      type={input.type} 
      placeholder={input.placeholder} 
    />
  );
}

render () {
  return (
    <div>
      { this.state.inputs.map(this.renderInput) }
      <button onClick={this.handleSubmit}>submit</button>
    </div>
  );
}

我发现的问题

  1. key 设置为索引是一种反模式。阅读更多 https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318

  2. 在 render 中绑定(bind) this 是一种反模式。使用 es7 类属性来解决这个问题。或者您可以在构造函数中绑定(bind)方法。阅读更多关于绑定(bind)的信息 https://medium.com/@housecor/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56#.uzdapuc4y

解决方案一:

constructor(props) {
  super(props);
  this.handleSubmit = this.handleSubmit.bind(this);
}

方案二:

handleSubmit = () => {
  // do you stuff
}

关于javascript - 如何循环表单输入并在 react 中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41219033/

相关文章:

html - 在 React 的 <a> 标签中执行 onClick() 操作和 href

reactjs - 如何在 React 中实现输入自动制表符(关注 keyup 事件中的下一个输入元素)?

javascript - 在不影响所有对象字段的情况下映射对象数组

javascript - 从对象中删除空对象、数组、字符串或整数

javascript - 为什么我所有包含的 php 文件都没有显示? (CSS 导航选项卡)

javascript - 当我在移动设备上上下滚动时,我的技能图表不会消失

javascript - 尝试更改输入 onChange 时遇到状态错误

javascript - 意外的 token ,但不确定原因

javascript - 递归范围函数不起作用

javascript - 带有或不带有 onMount 的 SvelteJS 组件