如何将项目置于React Native ListView中?

时间:2017-04-20 04:10:55

标签: javascript listview react-native functional-programming

我选择时尝试将项目置于水平列表视图中心。我当前的策略是首先测量项目并滚动到视图中引用项目的x坐标。

enter image description here

目前,只要我按下某个项目ListView滚动到最后x: 538

是否有更简单的方法来实现这一点,同时保持代码无状态/功能?

const ItemScroll = (props) => {

  const createItem = (obj, rowID) => {

    const isCurrentlySelected = obj.id === props.currentSelectedID

    function scrollToItem(_scrollViewItem, _scrollView) {
      // measures the item coordinates
      _scrollViewItem.measure((fx) => {
        console.log('measured fx: ', fx)
        const itemFX = fx;
        // scrolls to coordinates
        return _scrollView.scrollTo({ x: itemFX });
      });
    }
    return (
      <TouchableHighlight
        ref={(scrollViewItem) => { _scrollViewItem = scrollViewItem; }}
        isCurrentlySelected={isCurrentlySelected}
        style={isCurrentlySelected ? styles.selectedItemContainerStyle : styles.itemContainerStyle}
        key={rowID}
        onPress={() => { scrollToItem( _scrollViewItem, _scrollView); props.onEventFilterPress(obj.id, rowID) }}>
        <Text style={isCurrentlySelected ? styles.selectedItemStyle : styles.itemStyle} >
          {obj.title}
        </Text>
      </TouchableHighlight>
    )
  };
  return (
    <View>
      <ScrollView
        ref={(scrollView) => { _scrollView = scrollView; }}
        horizontal>
        {props.itemList.map(createItem)}
        {props.onItemPress}
      </ScrollView>
    </View>
  );
};

更新

有了@Ludovic的建议我现在已经切换到FlatList,我不确定如何触发带有功能组件的scrollToIndex。以下是我的新ItemScroll

const ItemScroll = (props) => {

  const {
      itemList,
      currentSelectedItem
      onItemPress } = props

  const renderItem = ({item, data}) => {
    const isCurrentlySelected = item.id === currentSelectedItem

    const _scrollToIndex = () => { return { viewPosition: 0.5, index: data.indexOf({item}) } }

    return (
      <TouchableHighlight
        // Below is where i need to run onItemPress in the parent
        // and scrollToIndex in this child.
        onPress={[() => onItemFilterPress(item.id), scrollToIndex(_scrollToIndex)]} >
        <Text style={isCurrentlySelected ? { color: 'red' } : { color: 'blue' }} >
          {item.title}
        </Text>
      </TouchableHighlight>
    )
  }
  return (
    <FlatList
      showsHorizontalScrollIndicator={false}
      data={itemList}
      keyExtractor={(item) => item.id}
      getItemLayout={(data, index) => (
          // Max 5 items visibles at once
          { length: Dimensions.get('window').width / 5, offset: Dimensions.get('window').width / 5 * index, index }
      )}
      horizontal        
      // Here is the magic : snap to the center of an item
      snapToAlignment={'center'} 
      // Defines here the interval between to item (basically the width of an item with margins)
      snapToInterval={Dimensions.get('window').width / 5}
      renderItem={({item, data}) => renderItem({item, data})} />
  );
};

3 个答案:

答案 0 :(得分:2)

viewPosition 道具将使您的项目居中。

flatListRef.scrollToIndex({ index: index, animated: true, viewPosition: 0.5 })

答案 1 :(得分:1)

在我看来,您应该使用FlatList

FlatList有一个方法scrollToIndex,允许直接转到数据项。它与ScrollView几乎相同,但更智能。可悲的是,文档很差。

这是我做的FlatList的一个例子

let datas = [{key: 0, text: "Hello"}, key: 1, text: "World"}]

<FlatList
    // Do something when animation ended
    onMomentumScrollEnd={(e) => this.onScrollEnd(e)} 
    ref="flatlist"
    showsHorizontalScrollIndicator={false}
    data={this.state.datas}
    keyExtractor={(item) => item.key}
    getItemLayout={(data, index) => (
        // Max 5 items visibles at once
        {length: Dimensions.get('window').width / 5, offset: Dimensions.get('window').width / 5 * index, index}   
    )}
    horizontal={true}
    // Here is the magic : snap to the center of an item
    snapToAlignment={'center'}  
    // Defines here the interval between to item (basically the width of an item with margins)
    snapToInterval={Dimensions.get('window').width / 5}    
    style={styles.scroll}
    renderItem={ ({item}) =>
        <TouchableOpacity
            onPress={() => this.scrollToIndex(/* scroll to that item */)}
            style={styles.cell}>
            <Text>{item.text}</Text>
        </TouchableOpacity>
    }
/>

有关FlatList的更多信息:https://facebook.github.io/react-native/releases/next/docs/flatlist.html

答案 2 :(得分:0)

flatlistRef.current.scrollToIndex({
                    animated: true,
                    index,
                    viewOffset: Dimensions.get('window').width / 2.5,
                  });

您可以尝试将viewOffset放入scrollToIndex属性中,它将处理您的组件偏移,我使用2.5使其在屏幕中间,因为我在每个部分显示5个项目,而焦点项目之一在屏幕中间