gpt4 book ai didi

javascript - 如何在 react-native 中渲染多组件并设置单独的状态?

转载 作者:行者123 更新时间:2023-11-30 15:20:02 25 4
gpt4 key购买 nike

我有一个组件会使用 map 来渲染多个复选框,并且每个复选框都有一个回调函数“onPress”,通过 props 获取,“onPress”函数将 setState 选中,但是现在当我点击一个复选框时,所有复选框都会被选中,这导致它们都使用相同的状态,我想选择我刚刚点击的每个复选框的目标,我知道我可以为每个复选框编写许多状态不同的“onPress”函数,但它看起来很愚蠢,我会添加更多 future 的复选框,解决任务的最佳和灵活的方法是什么?

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

最佳答案

您只需将 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>
)
})
}

关于javascript - 如何在 react-native 中渲染多组件并设置单独的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43867821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com