How do you add refs to functional components using

2019-04-05 11:16发布

问题:

My specific goal is to use the ScrollTo method of a ScrollView but maintain functional component structure.

More generally this requires getting ref to the current component which isn't possible with naked react native.

In Dec 2016 recompose added Allows handlers property of withHandlers to be a factory function but I can't quite figure out how to use it correctly.

How do you add refs to functional components using withHandlers in Recompose and call ScrollTo on a ScrollView?

回答1:

You can try something like this:

/* ... */

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)


回答2:

Personally I prefer to initiate Ref as a prop

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

And then just pass it to your stateless component

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


回答3:

Another way is to make a class as a ref store:

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);