繁体   English   中英

react native中文本输入的条件渲染

[英]Conditional rendering of a text Input in react native

你如何有条件地呈现一个 textInput 使得当 textInput 字符中的值text小于 6 时,它会在用户单击确定按钮时记录错误

const [text, setText] = useState('')
<TextInput
  style={styles.textInputStyle}
  value={text}
  onChangeText = {(text) => setText(text)}
  placeholder="Text"
  placeholderTextColor="#60605e" />
<TouchableOpacity style={styles.button}
  onPress={() => {setText(text)} }>
  <Text style={styles.buttonTitle}>OK</Text>
</TouchableOpacity>

你的onPress回调可以管理这个。 它需要检查text.length < 6 ,然后根据结果进行分支。 它可能看起来像这样(我删除了样式逻辑以展示回调):

const MyComponent = () => {
  const [text, setText] = useState('');

  return (
    <>
      <TextInput
         value={text}
         onChangeText = {(text) => setText(text)}
      />
      <TouchableOpacity
        onPress={() => {
          if(text.length < 6) {
            // Alert user of invalid input
            Alert.alert("Input must be less than 6 characters!") ;
            return;
          }
          // ... continue on to the desired task
        }}
      >
        <Text>OK</Text>
      </TouchableOpacity>
    </>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM