我正在尝试将模态实现到Listview中,其中每个列表组件都是可单击的,并显示带有相关信息的模态。我目前无法让这个工作。我的代码如下:
renderRow函数:
var modalState = false;
open = () => {
modalState = true;
}
close = () => {
modalState = false;
}
return (
<View>
<View style={{flexDirection: 'row', padding: 3}}>
<Card
>
<CardItem>
<TouchableHighlight
style={{padding: 15}}
underlayColor = 'transparent'
onPress = {() => {
modalState = true;
alert(modalState);
}}
>
<Text style = {{color:'grey'}}>{devices.name}</Text>
</TouchableHighlight>
<TouchableHighlight
style={{padding: 15}}
underlayColor = 'transparent'
onPress = {() => {
modalState = true;
alert(modalState);
}}>
<View>
<Text> </Text>
</View>
</TouchableHighlight>
</CardItem>
</Card>
</View>
<Modal isVisible={modalState}>
<Card>
<CardItem>
<View style = {styles.modal}>
<Text>{devices.name}</Text>
<Button
title = "close"
onPress = {() => {
modalState = false;
}}
/>
</View>
</CardItem>
</Card>
</Modal>
</View>
);
答案 0 :(得分:0)
你应该将modalState变量移动到类状态。 在你的代码中发生的是modalState正在正确地改变,但是它并没有强制组件重新渲染,因此modal没有接收到新的道具,this.setState应该解决这个问题。
class listWithModal extends React.Compoent {
constructor(props) {
super(props)
this.state = {
modalState = false
}
}
render() {
const {modalState} = this.state
const open = () => {
this.setState({ modalState: true })
}
const close = () => {
this.setState({ modalState: true })
}
return (
<View>
<View style={{ flexDirection: 'row', padding: 3 }}>
<Card
>
<CardItem>
<TouchableHighlight
style={{ padding: 15 }}
underlayColor='transparent'
onPress={() => open()}
>
<Text style={{ color: 'grey' }}>{devices.name}</Text>
</TouchableHighlight>
<TouchableHighlight
style={{ padding: 15 }}
underlayColor='transparent'
onPress={() =>open()}>
<View>
<Text> </Text>
</View>
</TouchableHighlight>
</CardItem>
</Card>
</View>
<Modal isVisible={modalState}>
<Card>
<CardItem>
<View style={styles.modal}>
<Text>{devices.name}</Text>
<Button
title="close"
onPress={() => close()}
/>
</View>
</CardItem>
</Card>
</Modal>
</View>
);
}
}