经常看到移动端的密码输入框包括微信、支付宝都很美观,这里使用react简单的模拟了一个类似的输入弹框。

先说一下思路:密码一般都是六位,在视觉上给每个数字加上边框看起来似乎是留个单独的input,其实不然,下面代码的实现通过一个input做输入,然后把输入的位数渲染到带边框的容器中,这样是实现了类似的效果。

类型Vue的案例实现见上面一篇文章。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// MyModal.tsx

import React, { useState } from "react";
import { Modal, Button, Input } from "antd";
import "./index.css";

const MyModal: React.FC<{}> = (props) => {
const [visible, setVisible] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(false);
const [code, setCode] = useState<string>("");
const [number, setNumber] = useState<number[]>([0, 1, 2, 3, 4, 5]);

const onChange = (e: any) => {
let v = e.target.value;
setCode(v);
};

const handleConfirm = () => {
setVisible(false);
};

const handleCancel = () => {
setVisible(false);
};

return (
<div>
<Button type="primary" onClick={() => setVisible(true)}>
点击弹框
</Button>
<Modal
width={704}
title="确认支付"
visible={visible}
onOk={handleConfirm}
onCancel={handleCancel}
destroyOnClose={true}
maskClosable={false}
cancelText="取消"
okText="确认"
confirmLoading={loading}
>
<div className="payContainer">
<p className="title">请输入支付密码</p>
<div className="inputBox">
{number.map((item, index) => (
<div className="codeItem" key={index}>
{code[index]}
</div>
))}
<Input.Password
className="codeInput"
value={code}
maxLength={number.length}
onChange={onChange}
visibilityToggle={false}
/>
</div>
</div>
</Modal>
</div>
);
};

export default MyModal;

css样式文件处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
.payContainer {
margin: 90px 0;
text-align: center;
}
.title {
font-size: 14px;
font-weight: 400;
color: #6b778c;
margin-bottom: 24px;
}
.inputBox {
position: relative;
width: 336px;
margin: 0 auto;
display: flex;
justify-content: space-between;
font-weight: bold;
}
.codeItem {
width: 48px;
height: 48px;
line-height: 48px;
text-align: center;
background: #ffffff;
border: 1px solid #ebecf0;
font-size: 26px;
}
.codeInput {
height: 48px;
position: absolute;
outline: none;
color: transparent;
caret-color: #ebecf0;
font-size: 28px;
padding: 0 14px;
letter-spacing: 48px;
width: 336px;
border: none;
background: none;
-webkit-appearance: none;
}
.codeInput:focus {
border: none !important;
box-shadow: 0 0 0 0 #fff;
}

简单的密码输入弹框案例完成,详见在线演示