导入 button
+ alert
import {Text, View, StyleSheet, Alert, Button} from 'react-native'
js
import React, {Component} from 'react'
import {Text, View, ScrollView, StyleSheet, Dimensions, Alert, Button} from 'react-native'
export default class FlexDirection extends Component{
render(){
return (
<View style={[styles.container]}>
<Button title='alert'/>
</View>
)
}
}
const styles = StyleSheet.create({
container:{
justifyContent:'space-around',
alignItems:'center'
},
})

添加alert
属性
js
<View style={[styles.container]}>
<Button
title='alert'
onPress={() =>{alert('我是一个按钮')}}
/>
</View>

在这里 alert 是RN里面的一个函数,并不是组件。
js
<Button
title='Alert.alert'
onPress={() =>{Alert.alert('我是一个按钮')}}
color={'red'}
/>
我们试一下 Alert.alert
的方法。 通过下面的效果图,我们很明显的能看到区别对吧。一个带标头,一个不带标头。

携带函数,内部再创建两个按钮
我们首先需要先定义一个箭头函数
js
createTwoAlertButton = () => {
Alert.alert(
"警告标题⚠️",
"警告内容⚠️",
[
{
text:"取消",
onPress:() => console.log('Cancel!'),
style:'cancel'
},
{
text:"确认",
onPress:() => console.log('Confirm!'),
style:'default'
}
]
)
}
然后再重新写一个 button
组件
js
<Button
title='创建两个按钮'
onPress={this.createTwoAlertButton}
color={'green'}
/>
这里需要注意这个语法:onPress={this.createTwoAlertButton}
然后我们从效果图中可以看到


随着按钮的点击,我们可以看到我们所绑定的逻辑

是可以成功运行输出的。
全部代码
js
import React, {Component} from 'react'
import {Text, View, ScrollView, StyleSheet, Dimensions, Alert, Button} from 'react-native'
export default class FlexDirection extends Component{
createTwoAlertButton = () => {
Alert.alert(
"警告标题⚠️",
"警告内容⚠️",
[
{
text:"取消",
onPress:() => console.log('Cancel!'),
style:'cancel'
},
{
text:"确认",
onPress:() => console.log('Confirm!'),
style:'default'
}
]
)
}
render(){
return (
<View style={[styles.container]}>
<Button
title='alert'
onPress={() =>{alert('我是一个按钮')}}
/>
<Button
title='Alert.alert'
onPress={() =>{Alert.alert('我是一个按钮')}}
color={'red'}
/>
<Button
title='创建两个按钮'
onPress={this.createTwoAlertButton}
color={'green'}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'space-around',
alignItems:'center'
},
})