如何以编程方式删除警报提示?
IT技术
javascript
reactjs
react-native
react-native-android
react-native-ios
2021-05-16 19:13:44
1个回答
为了实现您的要求,一个基本的解决方法是创建一个单独的组件来代替警报。
我编写的组件接受两个props。text
和visible
。
在您的屏幕内,您可以将其添加为:
import React from 'react'
[....]
export default class Screen extends React.Component {
state = {
visible: true,
text: "Loading... Please wait"
}
drawAlert() {
setTimeout(() => {
this.setState({text: "Will dismiss in 1 second"}, () => {
setTimeout(() => {
this.setState({visible: false})
}, 1000);
})
}, 4000); // fake API request
return (
<Alert text={this.state.text} visible={this.state.visible} />
)
}
render() {
return(
<Alert text={this.state.text} visible={this.state.visible} />
)
}
}
这是alert
组件
import React, { Component } from 'react'
import { View, TouchableOpacity, Text } from 'react-native'
export default class Alert extends Component {
state = {
text: this.props.text,
visible: this.props.visible
}
componentWillReceiveProps(nextProps) {
this.setState({text: nextProps.text, visible: nextProps.visible})
}
drawBox() {
if (this.state.visible) {
return(
<View style={styles.container}>
<View style={styles.boxContainer}>
<View style={styles.textContainer}>
<Text style={styles.text}>{this.state.text}</Text>
</View>
<TouchableOpacity onPress={this.props.onPress} style={styles.buttonContainer}>
<Text style={styles.buttonText}>OK</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
render() {
return(
<View style={styles.container}>
{this.drawBox()}
</View>
)
}
}
const styles = {
wrapper: {
flex: 1,
},
container: {
zIndex: 99999,
position: "absolute",
backgroundColor: "rgba(0, 0, 0, 0.1)",
top: 0,
left: 0,
right: 0,
bottom: 0,
justifyContent: 'center',
alignItems: 'center',
},
boxContainer: {
backgroundColor: "#FFF",
borderRadius: 2,
padding: 10,
width: 300,
borderColor: "rgba(0,0,0,.1)",
borderBottomWidth: 0,
shadowOffset: { width: 0, height: 2 },
elevation: 1,
padding: 20
},
textContainer: {
marginBottom: 20
},
text: {
color: "#424242",
fontFamily: "Roboto",
fontSize: 18
},
buttonContainer: {
alignItems: 'flex-start'
},
buttonText: {
color: "#009688"
}
}
希望能帮助到你。