[英]is there way to check and unchecked the "check-boxes" from my example?
這是我嘗試選中和取消選中“復選框”的示例,但我感到困惑,如果有人向我展示應該如何完成,我會很高興。
import React, { useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { CheckBox } from 'react-native-elements';
const NewPlaceScreen = props => {
const [checked, setChecked] = useState(false);
return (
<View>
<CheckBox
iconRight
right
title="apple"
checked={checked}
onPress={() => setChecked(true)}
/>
<CheckBox
iconRight
right
title="kiwi"
checked={checked}
onPress={() => setChecked(true)}
/>
</View>
);
};
NewPlaceScreen.navigationOptions = {
headerTitle: 'viewsqq'
};
const styles = StyleSheet.create({
TextStyle: {
fontWeight: 'bold',
color: 'grey'
}
});
export default NewPlaceScreen
這就是我上面的例子
按下時,您需要將它們設置為與之前狀態相反的狀態。 您可以使用 setState 回調來執行此操作:
onPress={() => setChecked(prev => !prev)}
目前,您的復選框都使用checked
的相同狀態變量,因此它們將保持同步 - 更改一個將更改另一個。 如果這不是您想要的,您應該為每個復選框創建一個單獨的狀態變量。
更新:
要獨立處理每個復選框,您需要為每個復選框創建狀態:
const [isAppleChecked, setIsAppleChecked] = useState(false)
const [isKiwiChecked, setIsKiwiChecked] = useState(false)
return (
<View>
<CheckBox
iconRight
right
title="apple"
checked={isAppleChecked}
onPress={() => setIsAppleChecked(prev => !prev)}
/>
<CheckBox
iconRight
right
title="kiwi"
checked={isKiwiChecked}
onPress={() => setIsKiwiChecked(prev => !prev)}
/>
</View>
)
您需要為每個框設置單獨的狀態,否則它們將始終顯示相同的內容。 並且您需要將新狀態設置為舊狀態的相反狀態:
const NewPlaceScreen = props => {
const [appleChecked, setAppleChecked] = useState(false);
const [kiwiChecked, setKiwiChecked] = useState(false);
return (
<View>
<CheckBox
iconRight
right
title='apple'
checked={appleChecked} // use the apple-specific state
onPress={() => setAppleChecked(prevState => !prevState)} // use the new apple state function
/>
<CheckBox
iconRight
right
title='kiwi'
checked={kiwiChecked} // use the new kiwi state
onPress={() => setKiwiChecked(prevState => !prevState)} // use the new kiwi function
/>
</View>
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.