【问题标题】:How do you add refs to functional components using withHandlers in Recompose and call ScrollTo on a ScrollView?如何在 Recompose 中使用 withHandlers 将 refs 添加到功能组件并在 ScrollView 上调用 ScrollTo?
【发布时间】:2018-01-22 12:41:30
【问题描述】:

我的具体目标是使用 ScrollView 的 ScrollTo method,但保持功能组件结构。

更一般地说,这需要获取 isn't possible with naked react native 的当前组件的引用。

2016 年 12 月 recompose 添加了 Allows handlers property of withHandlers to be a factory function,但我不太清楚如何正确使用它。

如何在 Recompose 中使用 withHandlers 向功能组件添加 refs 并在 ScrollView 上调用 ScrollTo?

【问题讨论】:

    标签: javascript react-native recompose


    【解决方案1】:

    你可以试试这样的:

    /* ... */
    
    const MyView = ({ onRef, children }) => (
        <View>
            <ScrollView ref={onRef} /* ... */>
                {children}
            </ScrollView>
        </View>
    )
    
    export default compose(
        withHandlers(() => {
            let myScroll = null;
    
            return {
                onRef: () => (ref) => (myScroll = ref),
                scrollTo: () => (value) => myScroll.scrollTo(value)
            }
        },
        lifecycle({
            componentDidMount() {
                this.props.scrollTo({ x: 0, y: 100, animated: true })
            }
        })
    )(MyView)
    

    【讨论】:

    • 这太棒了。谢谢!
    • 是的,太棒了!
    • 我不断得到 scrollTo 不是一个函数。我在其中添加了.root 并且它起作用了:myScroll.root.scrollTo(value) 不知道为什么会这样......
    【解决方案2】:

    我个人更喜欢将 Ref 作为道具来启动

      withProps(() => ({
        ref: React.createRef(),
      })),
    

    然后将其传递给您的无状态组件

    const MyComponent = ({ ref }) => <Foo ref={ref} />
    

    【讨论】:

    • 然后你将如何使用该 ref 滚动?
    • 只需将 ref 传递给您的滚动功能。
    • 我可能错了,但不是每次重新渲染时都会以这种方式重新创建 ref 吗?他们不应该是恒定的吗?
    【解决方案3】:

    另一种方法是将类作为参考存储:

    const Stateless = ({ refs }) => (
      <div>
        <Foo ref={r => refs.store('myFoo', r)} />
        <div onClick={() => refs.myFoo.doSomeStuff()}>
          doSomeStuff
        </div>
      </div>
    )
    
    class RefsStore {
      store(name, value) {
        this[name] = value;
      }
    }
    
    const enhancer = compose(
      withProps({ refs: new RefsStore() }),
    )(Stateless);
    

    【讨论】:

    • 嗯,最佳答案比这个怪物要优雅得多,但这是你可以让事情发生的另一种方式。
    猜你喜欢
    • 2017-12-24
    • 2018-03-16
    • 2019-12-16
    • 2017-10-13
    • 2020-10-31
    • 1970-01-01
    • 2017-12-31
    • 2020-01-27
    • 2017-08-15
    相关资源
    最近更新 更多