繁体   English   中英

React-Native 如何更改每个项目的 state 值?

[英]React-Native How to change state value for each item?

I have a 'touchableOpacity' where each time its pressed it shows the selected value, but when a value is selected every item gets that value.

我需要这样做: item 1 -> selectedValue3 item 2 -> selectedValue1 ...

 { this.state.proyectosConTodo.map((item,index)=>{ return ( <View style={{paddingBottom:12}}> <Grid> <Col> <View style={{height:40,justifyContent: 'center'}}> <Text numberOfLines={1} allowFontScaling={false} style={{color: '#45526e',fontFamily: 'Roboto-Regular',fontSize:15, alignSelf: 'flex-start'}}>{item.proyecto.titulo}</Text> </View> </Col> <Col> <TouchableOpacity style={{ height:40,borderWidth:1, borderRadius:4, borderColor: '#e0e4eb', justifyContent: 'center',backgroundColor: '#f3f4f6'}} onPress={()=>{ this.setAgentesReasignarEnviar(item,index) }}> <Text allowFontScaling={false} style={{color: '#45526e',fontFamily: 'Roboto-Medium',fontSize:15, marginLeft:10,marginRight:10}}>{this.state.txt_agenteProyecto}</Text> <Icon style={{position: 'absolute',top:13,right:10}} name={ 'chevron-down'} size={10} color={ '#45526e'}/> </TouchableOpacity> </Col> </Grid> </View> ) }) }

我认为这是你需要的:

setAgentesReasignarEnviar(item, index) {
    const result = this.state.proyectosConTodo.map(() => return item);
    this.setState({
        proyectosConTodo: result
    });
}

有关更多详细信息,请查看: 如何用“-”替换数组中的所有未定义值?

从您的代码片段看来,您的结构似乎是一个带有FlatList或类似内容的屏幕,可以呈现多个TouchableOpacity组件。 问题在于,每次单击单个TouchableOpacity时,它都会更改屏幕的 state(不仅仅是它本身),导致所有可触摸的不透明度都具有该值。

一种可能的解决方案是创建另一个组件,它呈现您的列表项并拥有自己的 state。 用于渲染它的项目可以作为道具传递,然后在该组件内调用setState不会影响其他列表项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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