我正在使用React Native FlatList和React Native Modal。
单击FlatList中的项目后,我只想查看1个模态(包含所选项目的详细信息)。
但是,如果FlatList中有4个项目,则选择1个项目会导致 弹出所有四个模式。
反正我只能在FlatList中为1个所选项目显示1个模式,而不是多个模式吗?
下面的代码段(由于不需要,一些代码行已删除):
constructor(props) {
super(props);
this.state = {
dataSource: [],
isLoading: true,
modalVisible: false,
}
}
setModalVisible = (visible) => {
this.setState({ modalVisible: visible });
}
viewModal(item, price) {
const { modalVisible } = this.state;
return (
<Modal
statusBarTranslucent={true}
animationType={"slide"}
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
}}
>
<View>
<View>
<View>
<Text>
Appointment Start Time:
</Text>
<Text>
{moment(item.time_start).format('h:mm a')}
</Text>
</View>
<View>
<Text>
Appointment End Time:
</Text>
<Text>
{moment(item.end_start).format('h:mm a')}
</Text>
</View>
<View style={styles.row}>
<Text>
Total:
</Text>
<Text>
{price}
</Text>
</View>
<View>
<View>
<Button
mode="outlined"
onPress={() => {
this.setModalVisible(!modalVisible);
}}
>
{'Cancel'}
</Button>
</View>
<View>
<Button
mode="contained"
onPress={() => {
this.setModalVisible(!modalVisible);
}}
>
{'Accept'}
</Button>
</View>
</View>
</View>
</View>
</Modal>
);
}
viewFreelancerTime() {
return (
<View>
<FlatList
renderItem={({ item }) => {
let totalPrice = (parseFloat(item.service_price) + parseFloat(item.service_deposit)).toFixed(2);
return (
<Container>
{this.viewModal(item, totalPrice)}
<TouchableNativeFeedback
onPress={() => {
this.setModalVisible(true);
}}
>
<View>
<View>
<Text>
{moment(item.time_start).format('h:mm a')}
</Text>
</View>
<View>
<Text>
{totalPrice}
</Text>
</View>
</View>
</TouchableNativeFeedback>
</Container>
);
}}
/>
</View>
);
}
render() {
return (
<>
<View style={{ flex: 1 }}>
{this.viewFreelancerTime()}
</View>
</>
);
};
答案 0 :(得分:1)
问题在于您正在使用renderItem方法渲染模态,因此每次选择一个项目时,模态都会在每个渲染的项目中打开。
要解决此问题,您将必须在FlatList的同一级别上渲染一个具有绝对位置的自定义Modal组件,并将选定的项目信息作为prop传递。
就是这样:
/// <summary>
/// Copies values in 'from' to 'to' if they are null in 'to'
/// </summary>
public static void CopyProperties(Employee from, Employee to)
{
if (from == null) return;
if (to == null) to = new Employee();
if (to.EmployeeID == 0) to.EmployeeID = from.EmployeeID;
if (to.EmployeeName == null) to.EmployeeName = from.EmployeeName;
if (from.ContactAddress == null) return;
if (to.ContactAddress == null) to.ContactAddress = new Address();
if (to.ContactAddress.Address1 == null)
to.ContactAddress.Address1 = from.ContactAddress.Address1;
if (to.ContactAddress.City == null)
to.ContactAddress.City = from.ContactAddress.City;
if (to.ContactAddress.State == null)
to.ContactAddress.State = from.ContactAddress.State;
if (to.ContactAddress.ZipCode == null)
to.ContactAddress.ZipCode = from.ContactAddress.ZipCode;
}
如果要实现无限滚动,建议您进行分页并使用FlatList原生道具。
Pd:为了减少由于状态更新而导致的重新渲染,我正在重用selectedItem状态,因此,如果它不为null,则该模式将是可见的