如果在注册 React Native 之前未按下复选框,则显示警报



我想强制用户在注册前按下复选框按钮,否则显示警告说"你应该同意我们的条款和政策;。这是我的代码,它确保所有字段都不是空的,我想检查复选框是否也被按下:

onSignUp(){
if(
this.state.email != '' &&
this.state.password != '' &&
this.state.name != '' 
){
const { email, password, name } = this.state;
firebase.auth().createUserWithEmailAndPassword(email, password)
.then((result) => {
firebase.firestore().collection("Users")
.doc(firebase.auth().currentUser.uid)
.set({
name,
email
})
console.log(result)
})
.catch((error) => {
console.log(error)
})
}
else{
alert("Make sure you filled all the fields with correct info!");
}


}

复选框按钮

<Checkbox style={{padding:'5%'}}  color="primary" label="I agree with Terms & Policies" />

为复选框创建一个状态,在值更改时更新它,并在创建用户之前进行检查。或者使用useRef()挂钩附加到复选框,并在创建用户之前直接检查其值。

以下内容应该有效:

使用状态

import React, { useState } from 'react';
import CheckBox from '@react-native-community/checkbox';
export function MyComponent(props) {
const [checkBoxState, setCheckBoxState]  = useState(false);
const doSignUp = () => {
if (!checkBoxState) {
/* display a warning */
} else {
/* continue with sign up */
}
}
return (
<CheckBox
value={checkboxState}
onValueChange={setCheckBoxState}
/>
{/* Have a button somewhere that calls doSignUp() */}
);
}

useRef

import React, { useRef } from 'react';
import CheckBox from '@react-native-community/checkbox';
export function MyComponent(props) {
const checkBoxRef = useRef(null);
const doSignUp = () => {
if (!checkBoxRef.current.value) {
/* display a warning */
} else {
/* continue with sign up */
}
}
return (
<CheckBox
ref={checkBoxRef}
value={false}
/>
{/* Have a button somewhere that calls doSignUp() */}
);
}

最新更新