[英]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.