【发布时间】:2018-12-26 15:32:08
【问题描述】:
我已从 NativeBase 导入 CheckBox。单击 Checkbox 时,它会调用 toggleCheckBox 函数从数组中添加或删除 item.ids,并根据数组的内容将标志设置为 true 或 false。
我可以看到 toggleCheckBox 函数正常工作,它正确设置了带有项目 id 的数组,并且在单击 CheckBox 时标志也很好。但是,尽管正确调用了切换函数,但单击复选框时不会选中 ListItem 内的复选框。
我还注意到单击 CheckBox 后会打印列表正上方的日志“MS CB2:”,但未打印列表“MS insideList:”内的日志。我假设在调用 toggleCheckBox 函数后未呈现 List 。 代码如下:
class MSScreen extends Component {
constructor(props){
super(props);
//this.toggleCheckbox = this.toggleCheckbox.bind(this);
this.state = {
isLoading: true,
checkboxes : [],
plans: {},
};
}
componentDidMount(){
console.log("MS inside componentDidMount");
fetch('http://hostname:port/getData')
.then((response) => {console.log('response'); return response.json();})
.then((responseJson) => {console.log('responseData: '+responseJson); this.setState({isLoading : false, plans : responseJson}); return;})
.catch((err) => {console.log(err)});
}
toggleCheckbox(id) {
let checkboxes = this.state.checkboxes;
if(checkboxes && checkboxes.includes(id)){
const index = checkboxes.indexOf(id);
checkboxes.splice(index, 1);
} else {
checkboxes = checkboxes.concat(id);
}
this.setState({checkboxes});
console.log("MS check a4: "+checkboxes && checkboxes.includes(id))
}
render() {
if (this.state.isLoading) {
return <View><Text>Loading...</Text></View>;
}
const plans = this.state.plans;
const { params } = this.props.navigation.state.params;
const checkboxes = this.state.checkboxes;
console.log("MS CB1: "+checkboxes)
return (
<Container>
<Content>
<View>
{console.log("MS CB2: "+checkboxes)}
<List
dataArray={plans.data}
renderRow={(item, i) => {
console.log('MS insideList : '+checkboxes && checkboxes.includes(item.id))
return(
<ListItem
key={item.id}
>
<Left>
<CheckBox
onPress={() => this.toggleCheckbox(item.id)}
checked={checkboxes && checkboxes.includes(item.id)}
/>
</Left>
<Text>
{item.name}
</Text>
</ListItem>)}}
/>
</View>
</Content>
</Container>
);
}
}
如何让 CheckBox 在 List 中被选中?
为了其他用户的利益,这里是基于 Supriya 在下面 cmets 中的建议的代码修复:
解决方案
<FlatList
extraData={this.state}
data={plans.data}
keyExtractor={(item, index) => item.id}
renderItem={({item}) => {
const itemName = item.name;
return(
<ListItem>
<CheckBox
onPress={() => this.toggleCheckbox(item.id)}
checked={checkboxes && checkboxes.includes(item.id)}
/>
<Body>
<Text style={styles.planText}>
{item.name}
</Text>
</Body>
</ListItem>)}}
/>
版本:
native-base@2.3.5
react-native@0.50.4
设备:安卓
带有 Expo 的 CRNA 应用
【问题讨论】:
-
你用 NativeBase KitchenSink 检查过这个吗?
-
很抱歉,我没有理解您的问题 Supriya。我已经提到了 Nativebase KitchenSink 代码。但是,我的问题是,如果我将带有硬编码值的复选框代码复制粘贴到列表之外,则复选框会被正确选中。但是,如果我将复选框放在列表中,尽管切换功能正常工作,但单击它时,复选框不会被选中。请注意,当在 List 内调用切换函数时,不会打印 List 内的 console.log 语句,只会打印 List 外的语句
-
github上有类似问题,github.com/GeekyAnts/NativeBase/issues/989
-
非常感谢 Supriya。我按照您提供的链接中的 FlatList 示例进行了操作。
标签: android react-native native-base