如何在渲染前四舍五入按钮?

Tom*_*scu 7 react-native

我想创建一个按钮组件,无论其尺寸如何,它都将自动具有圆角。

如您所知,要实现圆角,一种实现方法是将边框半径指定为按钮高度的一半。

我实现的方式是在自定义组件中使用如下onLayout功能:

 onLayout(event: LayoutChangeEvent) {
    const { height } = event.nativeEvent.layout;
    this.setState({ borderRadius: height / 2 });
  }
Run Code Online (Sandbox Code Playgroud)

问题在于该按钮最初将在屏幕上显示为矩形,并且仅在一毫秒后才会在拐角处变圆,从而导致闪烁。

我的猜测是onLayout在组件渲染之后调用该函数。

如何实施呢?谢谢!

Hen*_*hli 1

在计算 borderRadius 之前,您可以返回透明按钮,这将防止这种闪烁效果......

// you pass radius, and height from component state

const MyButton = ({ radius, height }) => {
   if (radius === null) return <View style={{ backgroundColor: transparent }}>...</View>

else return <View style={{ borderRadius: radius, backgroundColor: 'red' }}>...</View>;
};
Run Code Online (Sandbox Code Playgroud)