【问题标题】:React-Native How to change state value for each item?React-Native 如何更改每个项目的状态值?
【发布时间】:2020-03-10 12:23:58
【问题描述】:

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.

我需要这样做: 项目 1 -> selectedValue3 项目 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>
) }) }

【问题讨论】:

    标签: javascript arrays reactjs react-native


    【解决方案1】:

    我认为这是你需要的:

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

    更多详情,请查看:How to replace all undefined values in an array with "-" ?

    【讨论】:

      【解决方案2】:

      从您的 sn-p 看来,您的结构似乎是一个带有 FlatList 或类似内容的屏幕,可呈现多个 TouchableOpacity 组件。问题是每次单击单个TouchableOpacity 时,它都会改变屏幕的状态(不仅仅是它本身),导致所有可触摸的不透明度都具有该值。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-08
        相关资源
        最近更新 更多