【问题标题】:Is it possible to add a semicolon in TextInput?是否可以在 TextInput 中添加分号?
【发布时间】:2019-09-13 18:46:19
【问题描述】:

是否可以在 TextInput 字段中添加分号以便拆分输入文本?

我的意思不仅仅是一个占位符,我希望它永久存在。我想我可以使用两个 TextInput 字段,但我宁愿使用一个。

我想创建一个可以保存时间的输入字段,例如 00:00。

             <TextInput
                keyboardType='decimal-pad'
                maxLength={4}
                autoCorrect={false}
                onChangeText={sample=> props.textChange(sample)}
                value={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>

【问题讨论】:

  • 是的,有可能。但我们需要您进行尝试 - 我们可以帮助您进行尝试,但我们不会为您这样做。
  • 我的意思是肯定有不止一种方法可以解决这个问题。这完全取决于您希望用户如何提供他们的输入。你真的希望他们输入时间吗?
  • @ChristopherNgo 是的,我希望他们在一个 TextInput 中输入时间,例如 3:40。输出值为 340,但输入将在一个 TextInput 中分为两个部分。
  • 我不想吹牛,但是有大量的文章和项目可以满足您的要求
  • 简单,使用两个输入,然后使用 CSS 使其 看起来 像一个。

标签: reactjs react-native


【解决方案1】:

我做了一个例子,只是格式化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>
  )
}

Codepen here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-27
    • 2016-09-28
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    相关资源
    最近更新 更多