Рендеринг нескольких TextInput при получении JSON - React Native

Можно ли отображать несколько TextInputs из API с помощью React-Native? Я работаю над проектом, который извлекает JSON из API и сначала отображает список элементов (только заголовок) с использованием FlatList, затем я щелкаю один из них и перехожу на следующую страницу, которая показывает сведения об этом выбранном элементе. Однако в API будут постоянно добавляться новые документы, которые содержат разное количество TextInputs, некоторые могут иметь 3, некоторые 2 и так далее. Документ также содержит заголовок, текст, изображение, но их количество всегда будет одинаковым 1.

Файл JSON, который я получаю из API:

{  
  "results":[  
  {  

     "contract":{  
        "title":"Contract test",
        "content":"You can always follow the progress of your application 
  by logging on the the application portal."
     },

    "fillable_fields": {
        "FIELD_NAME_1": "FIELD_VALUE_1",
        "FIELD_NAME_2": "FIELD_VALUE_2",
        "FIELD_NAME_N": "FIELD_VALUE_N"
    },
     "picture":{  

 "medium":"https://www.healthcaredenmark.dk/media/11272/bridgeit_logo.png"
     }
  }
]
}

Мой код:

class DetailScreen extends React.Component {
    static navigationOptions = {
      title: 'Content of selected'
    };

    render() {
      const source = this.props.navigation.state.params.source;
      const item = this.props.navigation.state.params.item;
      let contract = "";
      let img = "";
      let inp = "";
      let content  = "";

      if (item != null) {
        contractTitle = item.contract.title;
        img = item.picture.medium;
        content = item.contract.content;
        inp = item.fillable_fields
      }

      return (   
        <View style = {styles.container}>
          <Text style = {styles.text}>{contractTitle} </Text>
          <Image
            style = {{width: 300, height: 128}}
            source = {{uri: img}}
          />

          <Text  style = {styles.text} > {content} </Text>
          <FlatList>
            <TextInput style = {{textAlign: 'center', borderWidth: 1, marginBottom: 7, height: 50}}>
              {inp}
            </TextInput>
          </FlatList>

          <Button title = "Go back to the list" onPress = {this._goHome}/>
        </View>
      );
    }
}
Как сделать HTTP-запрос в Javascript?
Как сделать HTTP-запрос в Javascript?
В JavaScript вы можете сделать HTTP-запрос, используя объект XMLHttpRequest или более новый API fetch. Вот пример для обоих методов:
1
0
250
1

Ответы 1

Если я хорошо понимаю, вы должны попробовать это:

renderInputFields = () => {
    let inputFieldsList = [];
    let arrayFromJson = //extract here your input fields array from JSON
    arrayFromJson.map((inputFieldItem) => {
         inputFieldsList.push(
             <TextInput style = {{textAlign: 'center', borderWidth: 1, marginBottom: 7, height: 50}}>
                 {inputFieldItem.text} //.text is example. you should use here what property you need
             </TextInput>)
    });

    return inputFieldsList;
}

 <FlatList>
     {this.renderInputFields()}
 </FlatList>

Дайте мне знать, если у вас есть какие-либо вопросы, или что-то не ясно.

пожалуйста, проверьте ниже!

user8603159 18.02.2019 15:08

Другие вопросы по теме