Reactjs 可以在TextInput中添加分号吗?
是否可以在TextInput字段中添加分号以拆分输入文本 我的意思不只是一个占位符,我希望它永久存在。我想我可以使用两个文本输入字段,但我宁愿使用一个 我想创建一个保存时间的输入字段,比如00:00Reactjs 可以在TextInput中添加分号吗?,reactjs,react-native,Reactjs,React Native,是否可以在TextInput字段中添加分号以拆分输入文本 我的意思不只是一个占位符,我希望它永久存在。我想我可以使用两个文本输入字段,但我宁愿使用一个 我想创建一个保存时间的输入字段,比如00:00 <TextInput keyboardType='decimal-pad' maxLength={4} autoCorrect={false}
<TextInput
keyboardType='decimal-pad'
maxLength={4}
autoCorrect={false}
onChangeText={sample=> props.textChange(sample)}
value={props.sample}
onKeyPress={props.sample}
/>
props.textChange(示例)}
值={props.sample}
onKeyPress={props.sample}
/>
我知道我可以这样做,但我想避免
<View style={styles.sampleContainer}>
<TextInput
keyboardType='decimal-pad'
maxLength={2}
autoCorrect={false}
onChangeText={sample1 => props.textChange(sample1)}
value={props.sample1}
onKeyPress={props.sample}
/>
<View style={{ borderBottomColor: 'black', borderBottomWidth: 1, borderTopColor: 'black', borderTopWidth: 1 }}>
<Text style={{ fontSize: 22 }}>:</Text>
</View>
<TextInput
keyboardType='decimal-pad'
maxLength={2}
autoCorrect={false}
onChangeText={sample2 => props.textChange(sample2)}
value={props.sample2}
onKeyPress={props.sample}
/>
</View>
props.textChange(示例1)}
值={props.sample1}
onKeyPress={props.sample}
/>
:
props.textChange(示例2)}
value={props.sample2}
onKeyPress={props.sample}
/>
我举了一个例子,仅在onChange
函数中格式化输入。但是,符号/冒号不是永久性的,因为在没有输入的情况下使用它意味着用空格填充输入,因此无法在值的开头键入。要使冒号永久存在,您需要编写一个函数,该函数将零填充任何长度不合适的值:
const FormattedInput = () => {
const [value, setValue] = React.useState("");
const onChange = (e) => {
const formattedValue = formatInput(e.target.value);
if (formattedValue.length < 6) {
setValue(formattedValue);
}
}
const formatInput = (input) => {
if (input.length > 2 && input[2] !== ":") {
return input.substring(0, 2) + ":" + input.slice(2);
}
return input;
}
return (
<div>
<input placeholder="00:00" type="text" onChange={onChange} value={value}/>
</div>
)
}
const FormattedInput=()=>{
const[value,setValue]=React.useState(“”);
const onChange=(e)=>{
const formattedValue=formattinput(即target.value);
如果(formattedValue.length<6){
设置值(格式化值);
}
}
常量格式输入=(输入)=>{
如果(input.length>2&&input[2]!=“:”){
返回input.substring(0,2)+“:”+input.slice(2);
}
返回输入;
}
返回(
)
}
代码笔。是的,这是可能的。但我们需要你去尝试——我们可以帮助你让这种尝试奏效,但我们不会为你这样做。我的意思是,肯定有不止一种方法可以做到这一点。这完全取决于您希望用户如何提供输入。你真的想让他们输入时间吗?@ChristophenGo是的,我想让他们在一个文本输入中输入时间,例如3:40。输出值将是340,但输入将在一个TextInput中分为两个部分。我不想吹嘘,但有大量的文章和项目完全按照您的要求进行简单,使用两个输入,然后使其看起来像使用CSS的一个。