[英]react native : Unable to uncheck checkbox
在我的示例中,我提供了一個復選框列表,但我無法取消選中復選框。 現在我只能檢查它們但不能取消選中。 我應該如何修復我的代碼才能正常工作? ?
const [checkList, setCheckList] = useState<any[]>(actionList.map(e => ({ key: e.key, checked: false })));
const isChecked = (key) => {
checkList.filter(e => e.key == key)[0].checked
}
const renderActionItem = ({ item, index }) => {
return (
<TouchableOpacity
key={index}
activeOpacity={.7}
style={styles.touchableOpacity}
onPress={() => { console.log(item) }}
>
<CheckBox
style={styles.checkBox}
tintColors={{ true: 'white', false: 'white' }}
value={isChecked(item.key)}
onValueChange={() => {
const newCheckList = checkList.slice()
newCheckList.forEach(e => {
if (e.key == item.key) {
e.checked = !e.checked
}
})
setCheckList(newCheckList)
}}
/>
<Text style={styles.labelText}>{`${item.sequenceID} . ${item.label}`}</Text>
</TouchableOpacity>
)
}
import React, { Component } from 'react';
import { CheckBox } from 'native-base';
import { View, Text, StyleSheet} from 'react-native';
class Row extends Component {
constructor(props) {
super(props);
this.state = { checked: false };
}
render() {
return (
<View style={styles.container}>
<CheckBox
onPress={() => this.setState({
checked: !this.state.checked
})}
checked={this.state.checked}
/>
<Text style={styles.text}>
{ props.data }
</Text>
</View>
);
}
}
export default Row;
只需使用狀態來管理您的項目,如下所示:
const renderActionItem = ({ item, index }) => {
const [checkbox, setCheckbox] = useState(false);
return (
<TouchableOpacity
key={index}
activeOpacity={.7}
style={styles.touchableOpacity}
onPress={() => { console.log(item) }}
>
<CheckBox
style={styles.checkBox}
tintColors={{ true: 'white', false: 'white' }}
value={isChecked(item.key)}
onValueChange={() => {
useState(!checkbox)
}}
/>
<Text style={styles.labelText}>{`${item.sequenceID} . ${item.label}`}</Text>
</TouchableOpacity>
)
}
然后根據 state 更改設置自定義檢查圖標。 或者,您可以按照此示例進行操作:請注意,在這種情況下,我使用 SelectMultiple 而不是復選框
import React, { Component } from 'react'
import { View } from 'react-native'
import SelectMultiple from 'react-native-select-multiple'
const fruits = ['Apples', 'Oranges', 'Pears']
// --- OR ---
// const fruits = [
// { label: 'Apples', value: 'appls' },
// { label: 'Oranges', value: 'orngs' },
// { label: 'Pears', value: 'pears' }
// ]
class App extends Component {
state = { selectedFruits: [] }
onSelectionsChange = (selectedFruits) => {
// selectedFruits is array of { label, value }
this.setState({ selectedFruits })
}
render () {
return (
<View>
<SelectMultiple
items={fruits}
selectedItems={this.state.selectedFruits}
onSelectionsChange={this.onSelectionsChange} />
</View>
)
}
}
export default App
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.