更改列表项的背景

时间:2017-09-19 13:21:52

标签: reactjs list react-native listitem react-native-flatlist

如何选择多个列表项的背景颜色?我正在使用react-native-accordianreact-native-collapsible并在内容中使用平面列表。

_renderContent(section, i, isActive)
{
 //console.log("MY DATA---",section.time_slots);
  return (
    <List
      style={inStyles.body}
      containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
        <FlatList
          data={section.time_slots}
          renderItem={
            ({ item,index }) =>
            (
             <ListItem
             onPress={() => this.selectSlot(item,section.date,index)}

             style = {[inStyles.list , {marginLeft : 15}, {marginRight : 5},
               {backgroundColor: (this.state.selectedItem[index]) ? 'green' : 'red'}]}
               title={`${item}`}
               containerStyle={{ borderBottomWidth: 0 }}
             />
          )
        }
          keyExtractor={item => section.date+item}
          ItemSeparatorComponent={this.renderSeparator}
          ListFooterComponent={this.renderFooter}
          />
      </List>
    );
}

我只想使用TouchableOpacity动态更改列表项的样式。但无法这样做。

1 个答案:

答案 0 :(得分:4)

您应该如下更改您的代码,您的课程将如下所示:

  contructor (props) {
    super(props)
    let selectedItemTemp = []
    for(let i=0; i<section.time_slots.length; i++) { //section.time_slots is your FlatList data
      selectedItemTemp.push(false)
    }
    this.state = {selectedItem: selectedItemTemp}
  }


  selectSlot = (item, section.date, index) => {
    let {selectedItem} = this.state
    selectedItem[index] = !selectedItem[index]
    this.setState({selectedItem})
    ... // your other codes
  }

  render() {
    return (
      ...
        <FlatList
          data={section.time_slots}
          renderItem={
            ({ item, index }) => (
              <TouchableOpacity
              onPress={() => this.selectSlot(item,section.date, index)}>
               <ListItem style = {[inStyles.list , {marginLeft : 15}, {marginRight : 5}, {backgroundColor: (this.state.selectedItem[index]) ? 'green' : 'white'}]}
                 title={`${item}`}
                 containerStyle={{ borderBottomWidth: 0 }}
               />
              </TouchableOpacity>
            )
          } {item => section.date+item}
          ItemSeparatorComponeultiple Selectiont={this.renderSeparator}
          ListFooterComponent={this.renderFooter}
        />
      ...
    );
  }