SmsInput.jsx 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import * as WebBrowser from "expo-web-browser";
  2. import * as React from "react";
  3. import { Div, Image, Text, Avatar, Input } from "react-native-magnus";
  4. import { Toast } from "@ant-design/react-native";
  5. import { Button } from "@ui-kitten/components";
  6. import { useInterval } from "ahooks";
  7. import { sendSms } from "../Utils/SmsUtil";
  8. export default function SmsInput({
  9. label,
  10. placeholder,
  11. labelWidth,
  12. phone,
  13. onCodeChange,
  14. type,
  15. takePhone = false,
  16. }) {
  17. const [code, setCode] = React.useState();
  18. const [interval, setInterval] = React.useState(null);
  19. const [count, setCount] = React.useState(60);
  20. React.useEffect(() => {
  21. if (takePhone) {
  22. sendSms(phone, type || "register")
  23. .then(() => {
  24. setCount(60);
  25. setInterval(1000);
  26. })
  27. .catch(e => {
  28. console.log(e);
  29. Toast.info(e.response.data.error);
  30. });
  31. }
  32. }, [takePhone]);
  33. useInterval(
  34. () => {
  35. setCount(count - 1);
  36. if (count === 0) {
  37. setInterval(null);
  38. }
  39. },
  40. interval,
  41. { immediate: true }
  42. );
  43. return (
  44. <Div row alignItems="center" px={4} py={10}>
  45. <Text mr={19} textAlign="right" fontSize="sm" w={labelWidth || 80}>
  46. {label}
  47. </Text>
  48. <Input
  49. placeholder={placeholder}
  50. fontSize="sm"
  51. bg="gray100"
  52. flex={1}
  53. h={32}
  54. mr={10}
  55. value={code}
  56. onChangeText={value => {
  57. setCode(value);
  58. onCodeChange(value);
  59. }}
  60. borderColor="gray200"
  61. />
  62. <Button
  63. onPress={() => {
  64. sendSms(phone, type || "register")
  65. .then(() => {
  66. setCount(60);
  67. setInterval(1000);
  68. })
  69. .catch(e => {
  70. console.log(e);
  71. Toast.info(e.response.data.error);
  72. });
  73. }}
  74. appearance="ghost"
  75. size="tiny"
  76. disabled={!phone || interval}
  77. >
  78. {interval ? `已发送(${count})S` : "发送验证码"}
  79. </Button>
  80. </Div>
  81. );
  82. }