简体   繁体   中英

How to render multi components and set individual status in react-native?

I have a component will use map to render multi checkbox, and each checkbox has a callback function "onPress" get by props, the "onPress" function will setState checked, but now when I click on one checkbox, all checkboxs will be chosed, it cause they all use the same state, the goal I wanna choose each checkbox what I just ckick on, I know I can write many state different "onPress" function for each checkbox, but it looks stupid, I will add more checkbox in the future, What's the best and flexiable way to solve the task?

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;

The behavior is choose all checkbox even though I only choose one now. 在此处输入图片说明

You can just pass the langauge ( note this is probably a typo for language ) variable to the function and us it to identify which one is being checked

  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>
      ) 
    })
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM