【发布时间】:2018-08-08 00:54:53
【问题描述】:
你会怎么做才能只启用用户希望启用的一个开关(切换)?
这是我的状态:
state = {
menuItems: [
{ title: 'Test1', switchValue: false },
{ title: 'Test2', switchValue: false }
]};
这是我的构造函数:
constructor(props: any) {
super(props);
this.toggle = this.toggle.bind(this);
}
这里是功能控制切换:
toggle(item: any) {
const menu = [...this.state.menuItems];
menu[item].switchValue = !menu[item].switchValue;
this.setState({ menu });
}
这是地图的样子:
public render() {
return (
<View style={styles.container}>
{this.state.menuItems.map((item, index) => (
<TouchableOpacity onPress={this.showSettingHint} key={item.title}>
<View style={[styles.rowContainer, index === 0 ? styles.topRowContainer : null]}>
<Text style={styles.title}>{item.title}</Text>
<Switch
onValueChange={this.toggle}
value={item.switchValue}
/>
</View>
</TouchableOpacity>
))}
</View>
);}
但是我收到了这样的错误:
undefined 不是对象(评估 'menu[item].switchValue')
【问题讨论】:
标签: react-native switch-statement toggle