提取JSON时呈现多个TextInput-React Native

时间:2019-02-18 13:01:08

标签: json react-native fetch textinput react-native-flatlist

是否可以使用React-Native从一个API渲染多个TextInput? 我正在一个项目中,该项目从API提取JSON,然后首先使用FlatList显示项目列表(仅标题),然后单击其中一个项目并导航到显示该所选项目详细信息的下一页。 但是,会不断在API中添加新文档,其中包含不同数量的TextInput,有些可能有3,有些是2,依此类推。文档还包含标题,文本,图像,但这些内容始终相同。

我正在从API提取的

JSON文件:

{  
  "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>
      );
    }
}

1 个答案:

答案 0 :(得分:0)

如果我很好理解,您应该尝试以下方法:

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>

如果您有任何问题或不清楚的地方,请告诉我。

相关问题