思路:
当输入到规定长度时,下一个输入框focus
import React, { useCallback, useRef } from "react";
import { TextInput, Text, StyleSheet } from "react-native";
import { RowView } from "../../constants/styled";
import { Subheading } from "react-native-paper";
import { bold } from "../../style/common";
const DOB: React.FC<any> = ({
year,
setYear,
month,
setMonth,
day,
setDay,
errorYear,
errorMonth,
errorDay,
}) => {
const yearRef = useRef(null);
const monthRef = useRef(null);
const dayRef = useRef(null);
const autoFocusedNext = useCallback(
(
setValue: (arg0: string) => void,
nestRef: React.MutableRefObject<any>,
length: number
) => (value: string) => {
setValue(value);
if (value.length === length) {
nestRef?.current?.focus();
}
},
[]
);
return (
<RowView flexEnd between height="50px">
<Subheading style={[bold, { flex: 1 }]}>DOB</Subheading>
<TextInput
ref={yearRef}
value={year}
onChangeText={autoFocusedNext(setYear, monthRef, 4)}
maxLength={4}
placeholder="year"
style={[styles.item, errorYear ? { borderBottomColor: "#f00" } : null]}
// keyboardType="email-address"
keyboardType="number-pad"
/>
<Line />
<TextInput
ref={monthRef}
value={month}
onChangeText={autoFocusedNext(setMonth, dayRef, 2)}
maxLength={2}
placeholder="month"
style={[styles.item, errorMonth ? { borderBottomColor: "#f00" } : null]}
keyboardType="number-pad"
/>
<Line />
<TextInput
ref={dayRef}
value={day}
onChangeText={setDay}
maxLength={2}
placeholder="day"
style={[styles.item, errorDay ? { borderBottomColor: "#f00" } : null]}
keyboardType="number-pad"
/>
</RowView>
);
};
const Line = () => <Text style={{ marginHorizontal: 10 }}>/</Text>;
export default DOB;
const styles = StyleSheet.create({
item: {
width: 60,
borderBottomWidth: 1,
borderBottomColor: "#333",
padding: 5,
color: "#666",
...bold,
},
});