[英]Conditional rendering of a text Input in react native
How do you render a textInput conditionally such that when the value text
in the textInput characters is less than 6, it logs an error when the user clicks the ok button你如何有条件地呈现一个 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>
Your onPress
callback can manage this.你的onPress
回调可以管理这个。 It needs to do a check for text.length < 6
and then branch based off of the result.它需要检查text.length < 6
,然后根据结果进行分支。 It might look like this (I removed the styling logic to showcase the callback):它可能看起来像这样(我删除了样式逻辑以展示回调):
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.