首页 > 解决方案 > 在像抽屉一样的反应原生中显示垂直文本

问题描述

我需要在垂直位置显示文本。文本将是动态的,因此可以短或长。我已经添加了我想要的截图。任何人都可以分享这种类型的ui的代码。提前致谢。

像这样

看到这个,这就是我得到的

<View>
  <View style={{}}>
    <View
      style={{ marginTop: 30, flexDirection: "row", justifyContent: "center" }}
    >
      <Text
        style={{
          textAlign: "center",
          fontSize: 20,
          alignSelf: "center",
          transform: [{ rotate: "90deg" }],
          color: "white",
          fontWeight: "bold",
        }}
      >
        Short
      </Text>
    </View>
  </View>

  <View style={{}}>
    <View
      style={{ marginTop: 30, flexDirection: "row", justifyContent: "center" }}
    >
      <Text
        style={{
          textAlign: "center",
          fontSize: 20,
          alignSelf: "center",
          transform: [{ rotate: "90deg" }],
          color: "white",
          fontWeight: "bold",
        }}
      >
        Long Text
      </Text>
    </View>
  </View>
</View>;

标签: javascripttypescriptreact-native

解决方案


如果您尝试一一应用这些转换,您将遇到麻烦<Text />。而是尝试在父级中应用转换,<View />这使您可以更好地控制正在发生的事情。

const App = () => {
  const {width: screenWidth, height: screenHeight} = Dimensions.get('window');
  const height = 80;

  return (
    <View
      style={{
        transform: [
          {rotate: '-90deg'}, // negative degrees is important for this calculations and have the text face the content as your desired result picture shows
          {translateX: -(screenHeight / 2)}, // rotation is being applied in the center so it's safe to move it half screen
          {translateX: height / 2}, // correct the x translation with half of our component height so it stays on screen
          {translateY: -screenWidth}, // rotation is being applied in the center so it's safe to move it full screen width
          {translateY: height / 2}, // correct the y translation with half of our component height so it stays on screen
        ],
        width: screenHeight, // swap screen width with screen height so the background covers the entirety of the screen
        height, // fixed height is important to apply corrections on transform you could also use a ref and get this size on runtime
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'green',
      }}>
      <Text
        style={{
          fontSize: 20,
          color: 'white',
          fontWeight: 'bold',
          margin: 10,
        }}>
        Short
      </Text>

      <Text
        style={{
          fontSize: 20,
          color: 'white',
          fontWeight: 'bold',
          margin: 10,
        }}>
        Long Text
      </Text>

      <Text
        style={{
          fontSize: 20,
          color: 'white',
          fontWeight: 'bold',
          margin: 10,
        }}>
        Very Long Long Text
      </Text>
    </View>
  );
};

你可以在这里查看结果。


推荐阅读