如何在每个optionCount()上添加TextInputs?

时间:2018-01-08 10:48:03

标签: arrays reactjs react-native

每当用户点击图标时,我想添加textInput组件。为此,我增加了答案。但这对我不起作用。所以,请建议任何解决方案。

class CreateSurvey extends Component {
  constructor(props) {
   super(props);
   var answers = [{answer: ''}];
   this.state = {
   answers,
   answerLength: answers.length
 };
}
optionCount() {
 this.setState({answerLength: answerLength + 1});
 this.state.answers.length = answerLength;
}
render(){
 return( 
  <View>
   <View>
    {
     this.state.answers.map((answer, index) =>
      <TextInput key={index} placeholder='Add answer variant'
        value={answer.answer}/>
       )
     }
   </View>
   <TouchableOpacity onPress={this.optionCount.bind(this)}>
    <EIcon name={'circle-with-plus'} />
   </TouchableOpacity>
  </View>
   )
  }
 }

enter image description here

1 个答案:

答案 0 :(得分:2)

这不是你应该如何增加数组的大小。它在技术上是有效的,但是map()只适用于数组中的每个,无论指定的大小如何。

看看:

&#13;
&#13;
class App extends React.Component {
  
  render() {
    let arr = new Array(4);
    arr[0] = 1;
    arr[1] = 2;
    return (
      <ul>
        {arr.map(item => <li>{item}</li>)}
      </ul>
    );
  }
}

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;

正如您所看到的,即使我们的数组长度为4,它也只有2个值。我们的map()只迭代两次,而不是4次。

要解决您的问题,请在answers阵列中添加其他对象。像这样:

optionCount() {
  let newAnswers = this.state.answers.slice();  //copy our answers array
  newAnswers.push({answer: ''}); //add a new answer object to our copy
  this.setState({answers: newAnswers}); //replace the old array with the new one
}