компонент рендеринга на основе выбранного элемента в представлении массива - PullRequest
0 голосов
/ 25 сентября 2018

Я работаю над проектом, в котором мне нужно предоставить список элементов из массива, в котором для одного из элементов установлено значение по умолчанию.Если пользователь нажимает на другой элемент, тогда флажок перемещается из элемента по умолчанию к выбранному элементу.

Например, если у меня есть массив [default: "Saab", "Volvo", "BMW"].Затем, если я нажму на Volvo, он получит атрибут по умолчанию.Я отфильтровал массив и обновил его до вновь выбранного элемента.У меня возникла проблема с отображением этого на компонентах представления, когда они уже отрисованы.Моя функция фильтра

selectItem(val){
  var currentDefault = this.state.vehicleList.find(function(element, index) {
    return element.default == true;
  });

  var currentVehicle = this.state.vehicleList.indexOf(currentDefault);
  var selectedItem = this.state.vehicleList.indexOf(val);

  if (currentVehicle != selectedItem){
    this.state.vehicleList[currentVehicle].default = false;
    this.state.vehicleList[selectedItem].default = true;
    this.state.pickedVehicle = this.state.vehicleList[selectedItem];
  } else {
    console.log('same vehicle');
  }   
}

Предполагаю ли я поместить элемент в состояние, чтобы заставить его измениться?

Я добавляю функцию рендеринга ниже.

_renderItem({item, key}) {

      const car = (<Icon name="car" size={16} color="grey" />)
      const bicycle = (<Icon name="bicycle" size={16} color="grey" />)
     color="black" />)
      const check = (<Icon name="check-square" size={30} color="green" />)



                        if (item.type == 'car'){
                            return (
                              <TouchableHighlight onPress={() => this.selectItem(item)} underlayColor={'transparent'}>
                                <LinearGradient key={key} style={{justifyContent: 'center', borderRadius: 30, width: 180, height: 120, alignSelf: 'center'}} colors={['#ff00ff', '#0066ff']}>
                                    {renderIf(item.default == true)(
                                            <Text key={key} style={{alignSelf: 'flex-end', backgroundColor: 'rgba(0,0,0,0)', marginRight: 5}}> 
                                              {check}
                                             </Text>
                                        )}
                                    <View style={{alignSelf: 'center', justifyContent: 'center', width: 40, height: 40, borderRadius: 60/2, backgroundColor: 'white'}}>
                                        <Text style={{alignSelf: 'center'}}>
                                        {car} 
                                        </Text>
                                    </View>
                                    <Text style={{marginTop: 5, fontWeight: 'bold', marginTop: 5, color: 'white', fontSize: 12, alignSelf: 'center', backgroundColor: 'rgba(0,0,0,0)',}}>
                                      {item.make} {item.model} {item.year}
                                    </Text>
                                    <Text style={{fontWeight: 'bold', color: 'white', fontSize: 12, alignSelf: 'center', backgroundColor: 'rgba(0,0,0,0)',}}>
                                     {item.licensePlate} 
                                    </Text>
                                </LinearGradient>
                              </TouchableHighlight>
                              )
                          }
                          if (item.type == 'bicycle') {
                            return (
                                <LinearGradient key={key} style={{justifyContent: 'center', borderRadius: 30, width: 180, height: 120, alignSelf: 'center'}} colors={['#99cc00', '#000099']}>
                                      {renderIf(item.default == true)(
                                            <Text key={key} style={{alignSelf: 'flex-end', backgroundColor: 'rgba(0,0,0,0)', marginRight: 5}}> 
                                              {check}
                                             </Text>
                                        )}
                                        <View style={{alignSelf: 'center', justifyContent: 'center', width: 40, height: 40, borderRadius: 60/2, backgroundColor: 'white'}}>
                                            <Text style={{alignSelf: 'center'}}>
                                            {bicycle} 
                                            </Text>
                                        </View>
                                        <Text style={{marginTop: 5, fontWeight: 'bold', marginTop: 5, color: 'white', fontSize: 12, alignSelf: 'center', backgroundColor: 'rgba(0,0,0,0)',}}>
                                          {item.make} {item.model} {item.year}
                                        </Text>
                                        <Text style={{fontWeight: 'bold', color: 'white', fontSize: 12, alignSelf: 'center', backgroundColor: 'rgba(0,0,0,0)',}}>
                                         {item.licensePlate} 
                                        </Text>
                                </LinearGradient>

                              )
                            }

как я добавляю компонент

{this.state.vehicleList[index].default  && (
                                            <Text key={key} style={{alignSelf: 'flex-end', backgroundColor: 'rgba(0,0,0,0)', marginRight: 5}}> 
                                              {check}
                                             </Text>
                                        )}

1 Ответ

0 голосов
/ 25 сентября 2018

Поскольку существует ограничение на отображение значка проверки рядом с элементом, вы можете добавить это условие вместе со значком во время рендеринга.Например, вам нужно отобразить компонент Icon на основе этого условия, вы должны добавить его следующим образом.

{this.state.vehicleList[indexOfTheItem].default && (<Icon/>)}

Значок будет отображаться, только если this.state.vehicleList [item] .default равен true

Компонент снова визуализируется при изменении состояния.Поскольку вы обновляете состояние каждого транспортного средства по умолчанию, вы можете использовать значение bool соответствующего транспортного средства в качестве условия рядом с ним.

...