首页 > 解决方案 > React Native marginTop 在 TouchableOpacity 中偏移文本位置

问题描述

所以我刚刚开始在 React Native 中开发并遇到这个问题,由于某种原因,当我尝试将 marginTop 设置为可触摸不透明度时,我的文本不会与可触摸不透明度一起“移动”。这就是我的意思:

在此处输入图像描述

这变成:

在此处输入图像描述

相关代码如下(第二张图)。对于第一张图片,代码完全相同,只是没有marginTop。这里是:

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from 'react-native';

export default class App extends Component {
  render() {
    return (
      <TouchableOpacity style={styles.loginButton}>
        <Text style={styles.buttonText}>Login</Text>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  loginButton: {
    backgroundColor: 'lightblue',
    height: '20%',
    justifyContent: 'center',
    borderRadius: 20,
    marginTop: 30%
  },
  buttonText: {
    textAlign: 'center',
    fontSize: 20,
  },
});

标签: androidreactjsreact-nativemobiletouchableopacity

解决方案


use actual pixel number instead of percent number

import {Dimensions} from 'react-native'
const {height} = Dimensions.get('window')
marginTop: 0.3 * height

try and you will get it right


推荐阅读