【问题标题】:Multiple switches enable all at once when generated from array react-native从 array react-native 生成​​时,多个开关同时启用
【发布时间】: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


    【解决方案1】:

    可能是切换函数需要菜单项的索引作为参数。

    toggle(item: any) {
      const menu = [...this.state.menuItems];
      menu[item].switchValue = !menu[item].switchValue;
    
      this.setState({ menu });
    }
    

    然后在您的 Switch 中,您没有传递菜单项的索引,我认为如果您像这样在 onValueChange 中传递索引,它会起作用:

          <Switch
            //Add index here
            onValueChange={this.toggle(index)}
            value={item.switchValue}
          />
    

    【讨论】:

    • 感谢您的帮助。我只是把你的答案和我的混在一起,但它不起作用。
    • 顺便说一句,我将 menuItems 从 state 更改为 array 并且它有效!
    猜你喜欢
    • 2018-09-13
    • 2017-10-30
    • 2021-08-05
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 2018-04-19
    相关资源
    最近更新 更多