如何在react-native中呈现多个组件并设置个别状态?

时间:2017-05-09 10:51:14

标签: javascript reactjs checkbox react-native

我有一个组件将使用map来渲染多个复选框,并且每个复选框都有一个回调函数“onPress”获取道具,“onPress”函数将setState检查,但现在当我点击一个复选框时,所有复选框都将选择,它导致他们都使用相同的状态,目标我想选择每个复选框我只是ckick,我知道我可以写每个复选框的许多状态不同的“onPress”功能,但它看起来很愚蠢,我会添加更多未来的复选框,什么是解决任务的最佳和最灵活的方式?

import React, { Component } from 'react'
import { View } from 'react-native'
import { CheckBox } from 'react-native-elements'

const styles = {
  CheckBox: {
    borderBottomWidth: 0.3,
    borderBottomColor: 'gray'
  },
  checkBox : {
    backgroundColor: "#ffffff",
    borderWidth: 0
  },
  text: {
    flex: 0.95,
    backgroundColor: "#ffffff"
  }
}

const languages = ["中文","英文","日文","韓文"]

class Language extends Component {

  constructor(props) {
    super(props);
    this.state = { checked: false };
  }

  onPress = () => {
    this.setState({ checked: !this.state.checked })
  }

  renderlanguages = () => {
    return languages.map((langauge) => { 
      return(
        <View key = { langauge } style = { styles.CheckBox }> 
         <CheckBox
            title = { langauge }
            iconRight
            containerStyle = { styles.checkBox }
            textStyle = { styles.text }
            checkedColor = 'red'
            checked = { this.state.checked }
            onPress = { this.onPress }
          />
        </View>
      ) 
    })
  }

  render(){
    return(
      <View>
        { this.renderlanguages() }
      </View>
    )
  }
}

export default Language;

行为是全选复选框,即使我现在只选择一个。enter image description here

1 个答案:

答案 0 :(得分:2)

你可以将langauge注意这可能是language )变量的错误传递给函数,并告诉我们确定正在检查哪一个

  onPress = (langauge) => {
    this.setState({ [langauge]: { checked: !this.state[langauge].checked } })
  }

  renderlanguages = () => {
    return languages.map((langauge) => { 
      return(
        <View key = { langauge } style = { styles.CheckBox }> 
         <CheckBox
            title = { langauge }
            iconRight
            //component = { () => {return <TouchableOpacity></TouchableOpacity>}}
            containerStyle = { styles.checkBox }
            textStyle = { styles.text }
            checkedColor = 'red'
            checked = { this.state[langauge].checked }
            onPress = { () => this.onPress(langauge) }
          />
        </View>
      ) 
    })
  }