как сделать ввод на основе количества элементов в массиве реагировать - PullRequest
0 голосов
/ 05 марта 2020

Существует список вопросов, сохраненных в состоянии listQuestion. Каждый вопрос будет иметь поле ввода ответа. Как сохранить введенное значение и как использовать onChangetext, чтобы сохранить значение для каждого вопроса?

state = {
    listQuestion: [],
  };
async componentDidMount() {
   let question = await AsyncStorage.getItem("QuestionUser");
   if (question) {
      this.setState({ listQuestion: JSON.parse(question) });
    }
 }
renderTableData() {
    return this.state.listQuestion.map(ques => {
      const { question } = ques;
      return (
        <View style={styles.headerBottom}>
          <View style={styles.nameView}>
            <Text style={styles.textName}>{question} </Text> // display question
            <Input></Input> // how to use value and onChangeText for each question
          </View>
        </View>
      );
    });
  }

Ответы [ 3 ]

0 голосов
/ 05 марта 2020

сначала вам нужно отрендерить все входные данные на основе вашего listQuestion внутри вашего рендеринга. Я предполагаю, что в массиве listQuestion для каждого вопроса он будет иметь уникальный идентификатор для каждого вопроса, на основе которого мы будем определять, какое значение изменяется.

{
 listQuestion.map((item, index) => {
   return (
       <Input value = {item.value} onChange = {(e) => {this.handleOnChange(e, 
 item.id)} }></Input>
   );
 });
}
// item.id <= it is the unique identifier for each question object.

теперь вам нужно создать функцию, которая будет обрабатывать onChange

handleOnChange(e, id) {
 const {listQuestion} = this.state;
 listQuestion.forEach((item, index) => {
   (item.id == id) {
     item.value = e.target.value;
   }
 })
 this.setState({listQuestion})
}

также внутри вашего конструктора

constructor(props) {
 super(props);
 this.state = {
  listQuestion: []
 }
 this.handleOnChange = this.handleOnChange.bind(this);
}

скажем, у вас нет уникального идентификатора, тогда вы можете положиться на индекс, чтобы вы могли изменить это ...

<Input value = {item.value} onChange = {(e) => {this.handleOnChange(e, 
 index)} }></Input>
// it will send the index along with event, hence we can change value in listQuestion on the basis of index.

и просто измените это в функции onChange

handleOnChange(e, questionIndex) {
 const {listQuestion} = this.state;
 listQuestion.forEach((item, index) => {
   (questionIndex == id) {
     item.value = e.target.value;
   }
 })
 this.setState({listQuestion})
}

// hence it will find the index in listQuestion array and change value of that particular index.
0 голосов
/ 05 марта 2020

Добавлено новое состояние для хранения ответов в форме:

listAnswers = {
 question1: value,
 ...
};

Создайте пользовательский компонент для ввода текста, чтобы мы могли предоставить дополнительные реквизиты.

state = {
 listQuestion: [],
  listAnswers: {},
};
handleInput = (name, value) => {
 this.setState({listAnswers[name]: value }); 
}

renderTableData() {
 return this.state.listQuestion.map(ques => {
  const { question } = ques;
  return (
    <View style={styles.headerBottom}>
      <View style={styles.nameView}>
        <TextInput style={styles.textName}>{question} </Text> // display question
        <Input name={question} value={this.state.listanswers[question] || ''} onPress={this.handleInput}></Input>
      </View>
    </View>
  );
 });
}

TextInput Component

const TextInputComponent = ({value, onChangeText, name, ...props}) => (
 <Input
    value={value}
    onChangeText={(value) => onPress(name, value)} //... Bind the name here
    {...props}
 />
);
0 голосов
/ 05 марта 2020

const quesIndex = listQuestion.findIndex ((Ques) => Ques == {target.value}); listQuestion [QuesIndex] = {target.value};

...