React Native 中的禁用按钮
我遇到登录问题,试图禁用与按钮的交互。 这个想法是当两个文本字段为空时禁用提交按钮,但是当为空或不为空时我会得到相同的结果(始终可单击,或始终不可单击)。下面我详细说明我的想法以及我如何实现它。
我有两个状态存储来自两个文本输入的值,然后我有一个函数“isEmpty”来咨询该状态是否为空(“”)。后来,在“提交”按钮中,我有一个属性“禁用”,该属性的值是 isEmpty 的结果,即,如果 isEmpty 为 true,则禁用为 true,并且除非填充文本输入,否则用户不会单击该按钮。我尝试了一些事情,例如更改其他替代方案的返回值,或更改禁用的值,但我没有好消息。
我从网络和本网站搜索,解决方案并不能解决我的问题。
这里我分离了一些函数、状态和属性的代码。
<View style={styles.submit}>
<TouchableOpacity
onPress={() => checkValidation()}
disabled={emptyFields}
>
<Text style={styles.button}> Submit </Text>
</TouchableOpacity>
</View>
检查空字段 ->通过 checkValidation 调用函数来确定文本输入是否为空
const checkEmptyFields = () => {
if (
(id === "" && psw === "") ||
(id === "" && psw !== "") ||
(id !== "" && psw === "")
)
setEmptyFields(true);
};
const checkValidation = () => {
checkEmptyFields();
verifyUser();
resetStates();
};
使用的状态
const [id, setId] = useState("");
const [psw, setPsw] = useState("");
const [emptyFields, setEmptyFields] = useState(false);
I'm in a login problem trying to disable a interaction with a button.
The idea is to disable a submit button when 2 text field are empty, but I have the same result when is empty or not (always clickable, or always not). Below I specify the idea that I have, and how I implement it.
I have two states that stores the values from two text input, then I have a function "isEmpty" that consult if that states are empty (" "). Later, in a button "Submit" I have a property 'disabled' that which value is the result of isEmpty, i.e., if isEmpty is true, disabled is true and the user won't click the button unless the text input are filled. I tried some things, like change the return for another alternatives, or change the value of disable but I don't have good news.
I search from the web and this site, and the solutions doesn't resolve my problem.
Here I detach some code of the function, states and properties.
<View style={styles.submit}>
<TouchableOpacity
onPress={() => checkValidation()}
disabled={emptyFields}
>
<Text style={styles.button}> Submit </Text>
</TouchableOpacity>
</View>
checkEmptyFields -> function call by checkValidation to determinate if the text inputs are empties
const checkEmptyFields = () => {
if (
(id === "" && psw === "") ||
(id === "" && psw !== "") ||
(id !== "" && psw === "")
)
setEmptyFields(true);
};
const checkValidation = () => {
checkEmptyFields();
verifyUser();
resetStates();
};
States used
const [id, setId] = useState("");
const [psw, setPsw] = useState("");
const [emptyFields, setEmptyFields] = useState(false);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现了问题。在禁用属性中,我评估仅在 onPress 函数中计算的状态。修复方法是将行 checkEmptyFields 复制到禁用的内容中。
I found the problem. In the property disabled, i evaluate a state that ONLY calculates in a onPress function. The fix was to copy the line checkEmptyFields inside the disabled.