javascript - React Native 多个开关

标签 javascript reactjs react-native

在 React-Native 上,我试图创建一个包含多个开关组件的屏幕,并且可以一次只选择一个。当组件加载时,只有第一个开关打开。如果你点击它,它会关闭,但如果你打开另一个,所有其他的都会关闭。

我不确定这里的方法是否正确,因为我对如何使用组件状态来执行此操作感到困惑。

在 JS 中,我会做一些类似于关闭所有开关的功能,但打开点击的开关,但我不明白如何使用状态。

提前致谢

import React from 'react'
import { ScrollView, Text, View, Switch } from 'react-native'

class switchScreen extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      trueSwitchIsOn: true,
      falseSwitchIsOn: false
    }
  }

  switch = (value) => {
    this.setState({ falseSwitchIsOn: value, trueSwitchIsOn: !value })
  }

  render () {
    return (
      <View>
        <Switch
          onValueChange={this.switch}
          value={this.state.trueSwitchIsOn}
        />
        <Switch
          onValueChange={this.switch}
          value={this.state.falseSwitchIsOn}
        />
        <Switch
          onValueChange={this.switch}
          value={this.state.falseSwitchIsOn}
        />
      </View>
    )
  }
}

最佳答案

我相信一个更优化的解决方案将最大限度地减少状态量和不一致数据的可能性。使用一个状态变量来跟踪哪个开关处于事件状态(如果有的话)可以很容易地解决您的问题。

import React from 'react'
import { ScrollView, Text, View, Switch } from 'react-native'

class switchScreen extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      activeSwitch: null,
    }
  }

  // A simple toggle method that takes a switch number
  // And toggles it between on / off
  toggleSwitch = (switchNumber) => {
    this.setState({
      activeSwitch: switchNumber === this.state.activeSwitch ? null : switchNumber
    })
  };

  // 
  switchOne = (value) => { this.toggleSwitch(1) };
  switchTwo = (value) => { this.toggleSwitch(2) };
  switchThree = (value) => { this.toggleSwitch(3) };

  render () {
    return (
      <View>
        <Switch
          onValueChange={this.switchOne}
          value={this.state.activeSwitch === 1}
        />
        <Switch
          onValueChange={this.switchTwo}
          value={this.state.activeSwitch === 2}
        />
        <Switch
          onValueChange={this.switchThree}
          value={this.state.activeSwitch === 3}
        />
      </View>
    )
  }
}

关于javascript - React Native 多个开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44251346/

相关文章:

javascript - useState() Hook 不会更新更改时的值

ios - react native iPhone X SafeAreaView

javascript - 为什么在 for 循环的 setTimeout 内放置警报会破坏警报?

javascript - 可以强制 chrome 按存储顺序迭代 "string numeric"键

javascript - Jquery Hover - 允许悬停在另一个 DIV 上出现在悬停按钮上

reactjs - react 路由器 v4。 "exact"prop 是否禁止任何嵌套路由?

javascript - 类型错误 : Cannot set property 'props' of undefined

reactjs - 使用 Redux Thunk 和 Apollo Graphql 进行 react - 如何访问 client.query?

react-native - React Native onPress 被自动调用

javascript - 我可以定义哪些字符允许 'break' 一个字吗?