问题
Is it possible to render multiple TextInputs from an API using React-Native? I am working on a project which fetches JSON from an API and first displays a list of Items (Only the title) using FlatList, then I click in one of them and navigates to next page which shows details of that selected item. However, there will be continuously new documents added in API which contains a different number of TextInputs, some might have 3, some 2 and so on. Document contains also a title, text, image but those will always be the same amount 1.
JSON file I am fetching from 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"
}
}
]
}
My code:
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:
If I understand well you should try this:
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>
Let me know if you have any question, or something is not clear.
来源:https://stackoverflow.com/questions/54747938/rendering-multiple-textinput-when-fetching-json-react-native