问题描述
问题::我正在使用React Native,并且我有一个SectionList,其中的自定义组件由Text元素和Switch元素组成。每个部分中的某些项目可以重复,如果我从第1部分切换项目“第3课”,我希望将其功能更改为其他“第3课”项也要打开。我该怎么做?
解决方法
您应该具有单独的开关状态,当打开开关时,将搜索相应的名称并将其打开。
工作示例:https://snack.expo.io/@msbot01/awkward-turkish-delight
import React,{ Component } from 'react';
import {
StyleSheet,Text,View,SafeAreaView,SectionList,Switch,} from 'react-native';
import Constants from 'expo-constants';
import Icon from 'react-native-vector-icons/FontAwesome';
import AwesomeIcon from 'react-native-vector-icons/FontAwesome';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default class App extends Component<Props> {
constructor(props) {
super(props);
this.state = {
isEnabled: true,DATA: [
{
title: 'Main dishes',data: [
{ name: 'Pizza',status: false },{ name: 'Burger',{ name: 'Risotto',],},{
title: 'Sides',data: [
{ name: 'French Fries',{ name: 'Onion Rings',{
title: 'Drinks',data: [
{ name: 'Water',{ name: 'Coke',{
title: 'Desserts',data: [
{ name: 'Cheese Cake',{ name: 'Ice Cream',{ name: 'Pizza',status: false }
],]
};
}
toggleSwitch(e) {
// console.log(DATA.length);
for(var i=0; i< this.state.DATA.length; i++){
// console.log(DATA[i].data)
for(var j=0; j< this.state.DATA[i].data.length; j++){
// console.log(DATA[0].data[j].name)
// console.log(this.state.DATA[i].data[j].name)
if(e==this.state.DATA[i].data[j].name){
// console.log('match found')
var tempData = this.state.DATA
if(tempData[i].data[j].status==true){
tempData[i].data[j].status = false
}else{
tempData[i].data[j].status =true
}
this.setState({
DATA:tempData
})
}
}
}
}
render() {
return (
<View style={{ flex: 1 }}>
<SectionList
sections={this.state.DATA}
keyExtractor={(item,index) => item + index}
renderItem={({ item }) => (
<View style={{ flexDirection: 'row',marginTop: 10 }}>
<Text style={{ fontSize: 14,marginTop: 5 }}>{item.name}</Text>
<Switch
trackColor={{ false: '#767577',true: '#81b0ff' }}
thumbColor={item.status ? '#f5dd4b' : '#f4f3f4'}
ios_backgroundColor="#3e3e3e"
onValueChange={()=>{this.toggleSwitch(item.name)}}
value={item.status}
/>
</View>
)}
renderSectionHeader={({ section: { title } }) => (
<Text
style={{
fontSize: 18,marginTop: 10,backgroundColor: 'red',color: 'white',width: '50%',}}>
{title}
</Text>
)}
/>
</View>
);
}
}