sweetalert
是一个 可以用来替换JavaScript“Alert”的漂亮的控件,用起来简单,而且有丰富的形式,在交互的过程中,用上sweetalert
会使你的交互模式提高一个 档次。
github的地址在这里。
NMP结合Browserify或Webpack等工具是安装 SweetAlert 的推荐方法。
npm install sweetalert --save
还可以在unpkg和jsDelivr 上找到SweetAlert并使用全局swal变量。
< script src = " https://unpkg.com/sweetalert/dist/sweetalert.min.js " > < / script >
直接来看看使用的实例,我们就能够清楚的了解sweetalert
,更多的例子可以参看官方实例。
错误提示
swal("Oops!", "Something went wrong!", "error");
一条警告消息,带有附加到确认消息的功能:
使用承诺:
swal({
title: "Are you sure?",
text: "Are you sure that you want to leave this page?",
icon: "warning",
dangerMode: true,
})
.then(willDelete => {
if (willDelete) {
swal("Deleted!", "Your imaginary file has been deleted!", "success");
}
});
const willDelete = await swal({
title: "Are you sure?",
text: "Are you sure that you want to delete this file?",
icon: "warning",
dangerMode: true,
});
if (willDelete) {
swal("Deleted!", "Your imaginary file has been deleted!", "success");
}
提示模式,其中记录了用户的输入:
使用承诺:
swal("Type something:", {
content: "input",
})
.then((value) => {
swal(`You typed: ${value}`);
});
const value = await swal("Type something:", {
content: "input",
});
swal(`You typed: ${value}`);
与 Fetch 结合使用:
使用承诺:
swal({
text: "Wanna log some information about Bulbasaur?",
button: {
text: "Search!",
closeModal: false,
},
})
.then(willSearch => {
if (willSearch) {
return fetch("http://pokeapi.co/api/v2/pokemon/1");
}
})
.then(result => result.json())
.then(json => console.log(json))
.catch(err => {
swal("Oops!", "Seems like we couldn't fetch the info", "error");
});
const willSearch = await swal({
text: "Wanna log some information about Bulbasaur?",
button: {
text: "Search!",
closeModal: false,
},
});
if (willSearch) {
try {
const result = await fetch("http://pokeapi.co/api/v2/pokemon/1");
const json = await result.json();
console.log(json);
} catch (err) {
swal("Oops!", "Seems like we couldn't fetch the info", "error");
}
}
如果你正在使用 React
,除了主库之外,你还可以使用 React
安装SweetAlert
,并轻松地将React
组件添加到警报中,如下所示:
import React from 'react'
import swal from '@sweetalert/with-react'
swal(
<div>
<h1>Hello world!</h1>
<p>
This is now rendered with JSX!
</p>
</div>
)
更多的文档在这里。