[英]How do you add refs to functional components using withHandlers in Recompose and call ScrollTo on a ScrollView?
My specific goal is to use the ScrollTo method of a ScrollView but maintain functional component structure. 我的具体目标是使用ScrollView的ScrollTo方法 ,但维护功能组件结构。
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. 在2016年12月重新组合添加允许withHandlers的处理程序属性是一个工厂函数,但我无法弄清楚如何正确使用它。
How do you add refs to functional components using withHandlers in Recompose and call ScrollTo on a ScrollView? 如何在Recompose中使用withHandlers向函数组件添加refs并在ScrollView上调用ScrollTo?
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)
Personally I prefer to initiate Ref as a prop 我个人更喜欢将Ref作为道具
withProps(() => ({
ref: React.createRef(),
})),
And then just pass it to your stateless component 然后将其传递给您的无状态组件
const MyComponent = ({ ref }) => <Foo ref={ref} />
Another way is to make a class as a ref store: 另一种方法是将类作为ref存储:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.