【问题标题】:React Native align icon left and text centeredReact Native 左对齐图标和文本居中
【发布时间】:2018-05-22 04:01:57
【问题描述】:

我对 React Native 很陌生,我正在尝试做一些非常简单的事情:

我想创建以下组件:

一个 TouchableHighlight,其图像左侧对齐,文本相对于 Touchable 居中。

我尝试了很多选项,例如为文本添加填充或边距,但这只会使按钮变大并且似乎不是最干净的方法。

这是我目前所得到的:

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <View style={styles.appContainer}>
        <TouchableHighlight onPress={() => {}} style={styles.button}>
          <View style={styles.btnContainer}>
            <Image source={require('./assets/ic_logout.png')} style={styles.icon} />
            <Text style={styles.btnText}>Log out</Text>
          </View>
        </TouchableHighlight>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  appContainer: {
    flex: 1,
    backgroundColor: 'lightgreen',
    alignItems: 'center',
    justifyContent: 'center'
  },
  btnContainer: {
    backgroundColor: '#1d2aba',
    paddingHorizontal: 60,
    paddingVertical: 10,
    flexDirection: 'row',
    alignItems: 'center',
    borderRadius: 5
  },
  button: {
    borderRadius: 5
  },
  icon: {
    transform: [{ rotate: '180deg'}],
    width: 25,
    height: 25
  },
  btnText: {
    textAlign: 'center',
    fontWeight: 'bold',
    fontSize: 16,
    color: 'white'
  }
});

export default App;


出于视觉目的:

这是 Snack 满足您的测试需求!
PS:已经尝试过this,但无济于事。

【问题讨论】:

  • 您想在图片和文字之间保留一些空间吗?
  • @Nirmalsinh 完全正确!我希望图像靠近左边框和按钮中间的文本,谢谢!
  • 请检查我的答案。希望对您有所帮助。
  • @Nirmalsinh 哇!发现!谢谢!
  • 很高兴帮助你,伙计。

标签: android ios reactjs react-native touchablehighlight


【解决方案1】:

这是您的解决方案。更新以下样式:

对于图标:

icon: {
    transform: [{ rotate: '180deg'}],
    width: 25,
    height: 25,
    position: 'absolute',
    left: 2, // Keep some space between your left border and Image
  },

对于文本:

 btnText: {
    textAlign: 'center',
    fontWeight: 'bold',
    fontSize: 16,
    color: 'white',
    height:'100%',
    width:'100%'
  }

您可以在代码中更新这两种样式并进行检查。

【讨论】:

    猜你喜欢
    • 2019-10-01
    • 1970-01-01
    • 2017-10-20
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2017-06-29
    相关资源
    最近更新 更多