问题描述
这里我要做的是,在 Picker 值更改时调用函数并尝试调用 for 循环并绘制 5 TextInput,但出现错误。 请帮助解决这个小错误,当我尝试直接调用 myloop 数组时,更改其生成的错误,即数组不能作为函数调用。
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:///Dsenze/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;
console.log("Array data" , PickerValueHolder)
this.setState({ PickerValueHolder }); // Set the new state
})
.catch((error) => {
console.error(error);
});
}
onPickerValueChange=()=>{
{myloop}
console.log("Picker change" , myloop);
// this.onPickerValueTextinput();
}
render() {
for (let i = 0; i < 5; i++) {
myloop.push(
<View key={<TextInput></TextInput>}>
<TextInput style={{ textAlign: 'center', marginTop: 5 }}
placeholder="Enter your name ">
</TextInput>
</View>
)
}
return (
<View style={styles.container}>
{/* {myloop} */}
{<Picker
selectedValue={this.state.selectedValue}
onValueChange={this.onPickerValueChange}>
{ this.state.PickerValueHolder.map((item, key)=>
<Picker.Item label={item.name} value={item.name} key={key} />
)}
</Picker>}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
}
});
谢谢
1楼
Fahad Mahmood
0
2020-01-12 06:12:40
您的目标是在 ValueChange 上呈现 5 个文本输入
和你所在州的布尔值
state = {
PickerValueHolder: [],
selectedValue: '',
isChange : false,
}
您的 onChange 函数,通过设置布尔值来应用任何条件来呈现这些项目:
onPickerValueChange=(itemValue, itemPosition)=>{
this.setState({isChange:true});
}
使一个函数显示 Items 呈现 5 个输入;
const displayItems = () => {
if (this.state.isChange) {
return for (let i=0; i<5; i++) {
return (
<View key={<TextInput></TextInput>}>
<TextInput style={{ textAlign: 'center', marginTop: 5 }}
placeholder="Enter your name ">
</TextInput>
</View>
);
}
}
};
使成为
return (
<View style={styles.container}>
{displayItems()}
<Picker
selectedValue={this.state.selectedValue}
onValueChange={this.onPickerValueChange}>
{ this.state.PickerValueHolder.map((item, key)=>
<Picker.Item label={item.name} value={item.name} key={key} />
)}
</Picker>
</View>
);