mardi 9 mai 2017

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.enter image description here




Aucun commentaire:

Enregistrer un commentaire