//在这里我试图生成动态UI。通过API,我以JSON格式获得了一些响应,我必须在UI上绘制它。就像没有定义任何" textinput"它应该动态生成。BELOW是一些示例JSON响应。可能会根据不同的请求进行更改。请帮忙,我被困在下面只是一个代码,我不知道该怎么做。
import * as React from 'react';
import { Text, View, StyleSheet, Alert, Picker } from 'react-native';
import { Constants } from 'react-native';
import { TextInput } from 'react-native-gesture-handler';
var myloop = [];
export default class UiDynamic extends React.Component {
// add a selectValue to your state to stop the overwriting
state = {
PickerValueHolder: [],
selectedValue: ''
}
componentDidMount() {
// remove the return
fetch('http://userapi/inventory/viewinventorytype', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"username" :"admin",
"password" :"admin"
})
}).then((response) => response.json())
.then((responseJson) => {
// use the inventoryTypeData as it is already an array
let PickerValueHolder = responseJson.inventoryTypeData;
for (let i = 0; i < PickerValueHolder.length; i++) {
datavalue=() => {
<Text>Hello ABhi</Text>
console.log("Hello ABhi");
}
}
this.setState({ PickerValueHolder }); // Set the new state
})
.catch((error) => {
console.error(error);
});
}
GetPickerSelectedItemValue=()=>{
Alert.alert(this.state.PickerValueHolder);
}
render() {
for (let i = 0; i < 10; i++) {
datavalue=() => {
<Text>Hello ABhi</Text>
console.log("Hello ABhi");
}
myloop.push(
<View key={<TextInput></TextInput>}>
<Text style={{ textAlign: 'center', marginTop: 5 }} >{<Text>Hello</Text>}</Text>
</View>
);
}
return (
<View style={styles.container}>
{this.datavalue.bind(this)}
{myloop}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
}
});
//以下是样本JSON响应。假设这里获得了四个属性及其数据类型,因此在UI 4" TextInput"应该生成。
{
"inventoryTypeData": [{
"data type": int,
"Field 1": ""
}, {
"data type": string,
"Field2": ""
}, {
"data type": int,
"Field 3": ""
}, {
"datatype": int,
"Field4": ""
}],
"success": "true"
}
import { TextInput } from 'react-native';
一旦您映射了对状态的回应 this.setState({ PickerValueHolder });
然后,您可以使用MAP函数在渲染方法中循环遍历
return(
<View style={styles.container}>
{this.state.PickerValueHolder.map(data=>(
<View>
<TextInput
placeholder={data.placeholder}
keyboardType={data.datatype==="int" ? 'numeric': 'default'}
onChangeText={(text) => this.setState({...this.state.value [data.name]: text })}
value={this.state.value[data.name]}
/>
<Button
onPress={this.handleButtonPress(data.name).bind(this)}
/>
<View/>
/>
))}
</View>
)
}```
So here you are checking if the datatype is an int and then setting the keyboard type to numeric
This is also setting all the changes to a value object in state.
The Button calls a function with the name of of the value related to the text input