使用 React Hooks 响应原生 onLayout [英] React Native onLayout with React Hooks

查看:38
本文介绍了使用 React Hooks 响应原生 onLayout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测量 React Native View 的大小 每次渲染时,并将其保存到状态.如果元素布局未更改,则效果不应运行.

I want to measure the size of a React Native View every time it renders, and save it to state. If element layout didn't change the effect should not run.

使用基于类的组件很容易,其中 onLayout可以使用.但是在使用 React Hooks 的函数式组件中我该怎么做?

It's easy to do with a class based component, where onLayout can be used. But what do I do in a functional component where I use React Hooks?

我已经了解了 useLayoutEffect.如果这是要走的路,你有一个如何使用它的例子吗?

I've read about useLayoutEffect. If that's the way to go, do you have an example of how to use it?

我制作了一个名为 useDimensions 的自定义钩子.这是我已经走了多远:

I made this custom hook called useDimensions. This is how far I've got:

const useDimensions = () => {
  const ref = useRef(null);
  const [dimensions, setDimensions] = useState({});
  useLayoutEffect(
    () => {
      setDimensions(/* Get size of element here? How? */);
    },
    [ref.current],
  );
  return [ref, dimensions];
};

我使用钩子并将引用添加到我想要测量其尺寸的视图中.

And I use the hook and add the ref to the view that I want to measure the dimensions of.

const [ref, dimensions] = useDimensions();

return (
  <View ref={ref}>
    ...
  </View>
);

我试过调试 ref.current 但没有发现任何有用的东西.我也在效果中尝试了 measure()钩子:

I've tried to debug ref.current but didn't find anything useful there. I've also tried measure() inside the effect hook:

ref.current.measure((size) => {
  setDimensions(size); // size is always 0
});

推荐答案

如果你想要一个更独立的版本,这里是 React Native 的自定义钩子版本:

If you could like a more self-contained version of this here is a custom hook version for React Native:

const useComponentSize = () => {
  const [size, setSize] = useState(null);

  const onLayout = useCallback(event => {
    const { width, height } = event.nativeEvent.layout;
    setSize({ width, height });
  }, []);

  return [size, onLayout];
};

const Component = () => {
  const [size, onLayout] = useComponentSize();
  return <View onLayout={onLayout} />;
};

这篇关于使用 React Hooks 响应原生 onLayout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆