我有 2 個用戶文本輸入,稱為搜索位置和坐標。我試圖在選中時使用復選框,允許編輯搜索位置并禁用坐標輸入,反之亦然,當未選中復選框時。
當我第一次運行代碼時,我可以編輯搜索位置并且坐標被禁用。當我選中復選框時,文本輸入作業正常,搜索位置被禁用并且坐標是可編輯的。但是,當我嘗試取消選中該復選框時,搜索位置仍處于禁用狀態,并且仍然可以編輯坐標。
我曾嘗試使用 useEffect 但我對此不太熟悉,也不知道這是否是正確的方法。我對用戶輸入使用 react 鉤子表單,我對復選框使用 react native 元素。
代碼:
export default function UserInput({ navigation }) {
const { handleSubmit, control } = useForm();
const [checkbox, setCheck] = useState(false);
const [edit1, setEdit1] = useState(true);
const [edit2, setEdit2] = useState(false);
const onSelect = () => {
if (!checkbox) {
setEdit1(false);
setEdit2(true);
}
setCheck(!checkbox);
};
return (
<View style={styles.formContainer}>
<Text style={styles.text}>Distance(km)</Text>
<Controller
name="distance"
control={control}
rules={{
required: true,
}}
render={({ field: { onChange, value } }) => (
<TextInput
placeholder="Enter your Distance"
style={styles.input}
onChangeText={onChange}
value={value}
/>
)}
/>
<Text style={styles.text}>Search Location</Text>
<Controller
name="searchLocation"
control={control}
rules={{
required: true,
}}
render={({ field: { onChange, value } }) => (
<TextInput
placeholder="Enter your Coordinates"
style={styles.input}
onChangeText={onChange}
value={value}
editable={edit1}
/>
)}
/>
<CheckBox
center
title="Current Location"
checked={checkbox}
onPress={onSelect}
/>
<Text style={styles.text}>Coordinates</Text>
<Controller
name="coordinates"
control={control}
rules={{
required: true,
}}
render={({ field: { onChange, value } }) => (
<TextInput
placeholder="Enter your Coordinates"
style={styles.input}
onChangeText={onChange}
value={value}
editable={edit2}
/>
)}
/>
</View>
);
}
uj5u.com熱心網友回復:
試試這個
const onSelect = () => {
if (!checkbox) {
setEdit1(false);
setEdit2(true);
} else {
setEdit1(true);
setEdit2(false);
}
setCheck(!checkbox);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/395411.html
下一篇:為什么這些鏈接不同并且作用相同?
