[英]How to change text immediately in onChangeText Callback?
I have a case i want to do "Write Time"我有一个案例我想做“写时间”
So I have a TextInput user can write a time "numbers" now as usually i set state with new char using onChangeText So now i want to replace the third character user typed with :
immediately and continue other numbers所以我有一个 TextInput 用户现在可以写一个时间“数字”,因为我通常使用 onChangeText 用新字符设置状态所以现在我想替换用户输入的第三个字符
:
立即并继续其他数字
So the final result should be所以最后的结果应该是
user type 123 should change to 12: immediately then continue 12:45
用户类型 123 应更改为 12:立即然后继续
12:45
But i can't achieve it :(但我无法实现它:(
code snippet代码片段
const [daysSelected, setDaysSelected] = useState([]);
// sample state after manipulated
daysSelected = [{
id: 1,
day: "Sunday",
morning: ['', ''],
evening: ['', ''],
}]
<TextInput
placeholder="07:00"
maxLength={5}
ref={ref}
style={styles.inputTime}
placeholderTextColor="#707070"
value={String(daysSelected[item.id]?.morning[0])}
onChangeText={(text) => {
setDaysSelected((prevState) => {
let x = prevState[item.id].morning[0].replace(3, ':');
console.log('shouldReplaced?', x); // not works well :\
console.log('txt', prevState[item.id]?.morning[0]);
prevState[item.id].morning[0] = text;
return [...prevState];
});
}
/>
To this fix this problem here is an approach I suggest:为了解决这个问题,我建议采用一种方法:
Here is a simple snippet of code to achieve this.这是实现此目的的简单代码片段。
const [inputTime, setTime] = React.useState(null);
return (
<View style={styles.container}>
<TextInput
maxLength={5}
placeholder="07:00"
placeholderTextColor="#707070"
onBlur={(e) => {
let { text } = e.nativeEvent;
let values = text.split(":");
let value = "";
if(values.length==1){
value = values[0].substring(0,4).padStart(4, 0);
value = value.substring(0, 2) + ':' + value.substring(2);
setTime(value);
}else if(values.length==2){
value = `${values[0].padStart(2, 0)}:${values[1].padEnd(2, 0)}`;
setTime(value);
}
else{
console.log('wrong input')
}
}}
/>
<Text>{`Formatted time is ${inputTime}`}</Text>
</View>
);
Here is the Snack https://snack.expo.io/@saachitech/477b89这是小吃https://snack.expo.io/@saachitech/477b89
Tested with below conditions在以下条件下测试
Input 123 will be converted to 01:23
Input 1234 will be converted to 12:34
Input 12121 will be converted to 12:12
Input 12:1 will be converted to 12:10
Input 1:23 will be converted to 01:23
Input 12:23 won't have any effect and remain 12:23
Input 01:23 won't have any effect and remain 01:23
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.