import { forwardRef, useCallback, useImperativeHandle, useRef, useState } from 'react'
import styled from 'styled-components'
/**
* isPsw: 是否是密码键盘
* inputedValue: 回调用户的输入
*/
const JPasswordField = forwardRef(function ({ isPsw, inputedValue, autoFocus }, ref) {
const [value, setValue] = useState('')
const pswRef = useRef('******')
const inputRef = useRef()
useImperativeHandle(
ref,
() => ({
clear: () => {
_onChangeText('')
},
focus: () => {
inputRef.current.focus()
}
}),
[_onChangeText]
)
const _onChangeText = useCallback(
text => {
pswRef.current = text.padEnd(6, '*')
setValue(text)
if (text.length === 6) {
inputRef.current?.blur()
inputedValue?.(text)
}
},
[inputedValue]
)
return (
<InputWrapper onPress={() => inputRef.current?.focus()}>
<TextInput
autoFocus={autoFocus}
ref={inputRef}
maxLength={6}
value={value}
keyboardType="number-pad"
onChangeText={_onChangeText}
/>
{pswRef.current.split('').map((v, index) => (
<DotText isPsw={isPsw} key={index}>
{v !== '*' ? (isPsw ? '·' : v) : ''}
</DotText>
))}
</InputWrapper>
)
})
const InputWrapper = styled.Pressable`
flex-direction: row;
justify-content: space-around;
`
const TextInput = styled.TextInput`
position: absolute;
left: -99999px;
z-index: -1;
height: 60px;
width: 100%;
`
const DotText = styled.Text`
width: 46px;
height: 60px;
line-height: 80px;
border-radius: 4px;
font-size: 100px;
border: 1px solid #d1d1d1;
text-align: center;
${p =>
!p.isPsw && {
fontSize: 30,
lineHeight: '60px'
}};
`
export default JPasswordField
密码键盘
网友评论