问题描述
我已经在expo中创建了一个应用程序,该应用程序具有各种字段的形式,并且使用邮件和手机号码进行otp验证。最初应禁用“提交”按钮,并且只有在输入了值并且同时验证了两个OTP的情况下,才应启用“提交”按钮。有人可以帮助提供本机响应中的状态标志吗?
解决方法
我将假定您正在使用Button
中的本机react-native
组件。
- 使用按钮组件的
disabled
道具。如果设置为true
,它将禁用按钮的所有交互。
<Button disabled={true} />
- 在更复杂的情况下,您可以将禁用的prop设置为这样的状态变量。
<Button disabled={buttonStatus} />
这是一个基于TextInput
组件的工作示例。
import React,{ Component } from "react";
import { TextInput,Button } from "react-native";
const App = () => {
const [value,onChangeText] = React.useState("");
const [value2,onChangeText2] = React.useState("");
const [buttonStatus,setButtonStatus] = React.useState(true);
const inputChangeHandler = () => {
if (value.length > 0 && value2.length > 0) {
setButtonStatus(false);
}
};
return (
<>
<TextInput
style={{ height: 40,borderColor: "gray",borderWidth: 1 }}
onChangeText={(text) => onChangeText(text)}
onChange={inputChangeHandler}
value={value}
/>
<TextInput
style={{ height: 40,borderWidth: 1 }}
onChangeText={(text) => onChangeText2(text)}
onChange={inputChangeHandler}
value={value2}
/>
<Button
disabled={buttonStatus}
title="Learn More"
color="#841584"
accessibilityLabel="Learn more about this purple button"
/>
</>
);
};
export default App;
如果您想实时更新按钮的状态,请使用TextInput的onChange
属性,或者如果您想在输入焦点不在焦点时更新状态,请使用{{1} }。
这是Expo
上的实时演示 ,使用钩子禁用按钮。仅当两个输入中都没有空字符串时,按钮才会启用。
import React,{ useEffect,useState } from 'react';
import { Button,Text,TextInput,View } from 'react-native';
const App = () => {
const [description,setDescription] = useState('');
const [amount,setAmount] = useState('');
const [disable,setDisable] = useState(true);
useEffect(() => {
(amount && description) ? setDisable(false) : setDisable(true);
},[amount,description]);
return (
<View>
<TextInput value={description} placeholder='Enter a description'
onChangeText={text => setDescription(text)}
/>
<TextInput value={amount} placeholder='Enter the amount in $'
keyboardType='numeric' onChangeText={text => setAmount(text)}
/>
<Button disabled={disable} title='Add' />
</View>
)
}
export default App;