本文基于Expo环境和react-native-toast-message↗ 2.2.1编写。 React Native CLI环境也可以采用相同方式。

npm install react-native-toast-message/app/_layout.tsx中,按以下方式配置。import Toast from 'react-native-toast-message';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<View>
{children}
<Toast />
</View>
);
}app.tsx中,按以下方式配置。import Toast from 'react-native-toast-message';
export function App( props: any ) {
return (
<>
{/* ... */}
<Toast />
</>
);
}import Toast from 'react-native-toast-message';
import { Button } from 'react-native'
export function Page() {
const showToast = () => {
Toast.show({
type: 'success',
text1: 'Hello',
text2: 'This is some something 👋'
});
}
return (
<Button
title='Show toast'
onPress={showToast}
/>
)
}/app/_layout.tsx(Expo)或app.tsx(React Native CLI)中进行以下配置。
示例中定义了三类Toast:success和error修改默认样式,tomatoToast则使用自定义布局。import Toast, { BaseToast, ErrorToast } from 'react-native-toast-message';
const toastConfig = { // config 변수 추가
success: (props) => (
<BaseToast
{...props}
style={{ borderLeftColor: 'pink' }}
contentContainerStyle={{ paddingHorizontal: 15 }}
text1Style={{
fontSize: 15,
fontWeight: '400'
}}
/>
),
error: (props) => (
<ErrorToast
{...props}
text1Style={{
fontSize: 17
}}
text2Style={{
fontSize: 15
}}
/>
),
tomatoToast: ({ text1, props }) => (
<View style={{ height: 60, width: '100%', backgroundColor: 'tomato' }}>
<Text>{text1}</Text>
<Text>{props.uuid}</Text>
</View>
)
}
export default function Page() {
return (
<View>
{children}
<Toast config={toastConfig} />
</View>
);
}import Toast from 'react-native-toast-message';
import { Button } from 'react-native'
export function Page() {
const showToast = () => {
Toast.show({
type: 'tomatoToast',
props: { uuid: 'uuid example' }
});
}
const showErrorToast = () => {
Toast.show({
type: 'error',
text1: 'Error',
text2: 'This is some something 👋'
});
}
return (
<Button
title='Show toast'
onPress={showToast}
/>
)
}