【问题标题】:How can I use refs to set callbacks on a FlatList?如何使用 refs 在 FlatList 上设置回调?
【发布时间】:2019-09-25 21:46:57
【问题描述】:

我正在尝试使用 refs 命令式地设置我的 FlatList 的 onEndReached 属性。有没有办法做到这一点?

我已经修改了一个 example from the PR PR,它添加了 setNativeProps,它可以在一段时间内将颜色从黑色切换为白色,但无法调用 onEndReachedonScroll

谁能帮我理解我做错了什么?

export default class Testing extends React.Component {
  componentDidMount() {
    let tick = 0
    this.list.setNativeProps({
      onEndReached: info => {
        // NEVER CALLED ????
        console.log('L231 on Scroll info ===', info)
      },

      onScroll: info => {
        // NEVER CALLED ????
        console.log('L250 info ===', info)
      },

      // Background DOES flash red on load... ???? 
      style: { backgroundColor: 'red' }
    })
    setInterval(() => {
      this.list.setNativeProps({
        onEndReached: info => {
          console.log('L231 on Scroll info ===', info)
        },

        // Background DOES toggle black and white... ???? 
        style: { backgroundColor: tick++ & 2 ? 'white' : 'black' }
      })
    }, 1000)
  }

  render() {
    return (
      <View style={styles.container}>
        <FlatList
          ref={component => (this.list = component)}
          style={{ backgroundColor: 'black' }}
          data={[{ key: 'a' }, { key: 'b' }]}
          renderItem={({ item }) => <Text>{item.key}</Text>}
        />
      </View>
    )
  }
}

我尝试过的事情

直接在this.list上设置onEndReached ????

export default class Testing extends React.Component {
  componentDidMount() {
    this.list.onEndReached = info => {
        // NEVER CALLED ????
        console.log(info)
    }
  }

【问题讨论】:

  • 你想做什么?我不认为那些是原生道具,你应该可以在不使用原生道具的情况下做this.list.onEndReached。您可以在这里查看可用的内容:facebook.github.io/react-native/docs/direct-manipulation
  • 我的最终目标是创建一个使用钩子创建无限分页列表的库,用户所要做的就是提供一个加载方法并将自定义钩子返回的 ref 设置为他们的 FlatList。这意味着我需要能够设置 onEndReached 并最终甚至能够强制设置 FlatList 上的 data 属性。那有意义吗?我尝试设置 this.list.onEndReached ,但也没有用。

标签: react-native react-native-flatlist react-ref


【解决方案1】:

我遇到了一个非常相似的问题,我解决这个问题的一种方法是使用高阶组件 (HOC)。使用 HOC,您可以以最小的干扰覆盖任何您想要的道具。

HOC Example/Info

【讨论】:

  • 点评来源: 请在您的答案中添加一些示例源代码。欢迎提供解决方案的链接,但请确保您的答案在没有它们的情况下有用:add context around the link 这样您的其他用户就会知道它是什么以及为什么会出现,然后引用您链接到的页面中最相关的部分如果目标页面不可用。答案只不过是一个链接may be deleted。见:How do I write a good answer?
猜你喜欢
  • 2017-11-04
  • 1970-01-01
  • 2013-12-14
  • 2016-03-04
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
相关资源
最近更新 更多