setState反应生成数组结果

时间:2018-09-20 09:11:07

标签: javascript reactjs ecmascript-6

如何在onChange事件上将索引推入数组位置?假设用户可以在任何输入上键入内容,并且我可以获取数组中的值,则位置必须与输入的索引匹配

onChange = () => {
    //so that I get, console.log(this.state.inputGroup)
    //expected ['value1', 'value2', 'value3']
}

render() {
    return(
        <div>
            <input onChange={e => this.onChange(1, index)} type="text"/>
            <input onChange={e => this.onChange(2, index)} type="text"/>
            <input onChange={e => this.onChange(3, index)} type="text"/>
        </div>
    )
}

2 个答案:

答案 0 :(得分:4)

您需要将值从输入传递给onChange方法。 因此,您通过了e.target.value。固定索引是第一个参数,这就是指向数组索引的方式。

<input onChange={(e) => { this.onChange(1, e.target.value) }} type="text"/>

onChange方法

onChange = (inputIndex, textValue) => {
   //I assume that array of size equal to inputs quantity already is 
   //declared with ex. empty strings (you can initialize that in 
   //component constructor)

   const inputGroup = this.state.inputGroup
   inputGroup[inputIndex] = textValue

   this.setState({ inputGroup })
}

顺便说一句。您可能想以0开始输入索引:)否则,数组的0元素将永远不会被任何输入使用。

答案 1 :(得分:0)

class Test extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      inputGroup: [null, null, null]
    }
  }

  onChange(index, e) {
    const inputGroupState = this.state.inputGroup;
    inputGroupState[index] = e.target.value;

    this.setState({
        inputGroup: inputGroupState
      },
      () => {
        console.log(this.state.inputGroup)
      }
    );
  }

  render() {
    return ( 
      <div>
       <input onChange = {e => this.onChange(0, e)} type = "text" / >
       <input onChange = {e => this.onChange(1, e)} type = "text" / >
       <input onChange = {e => this.onChange(2, e)} type = "text" / >
      </div>
    )
  }
}

ReactDOM.render( < Test / > , document.querySelector("#app"))
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}
<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>