React Native对齐图标左侧,文本居中

3
我对React Native还比较新,正在尝试做一些非常简单的事情:
我想创建以下组件:
左侧有图像,文字相对于可触摸区域居中的“TouchableHighlight”。
我尝试了许多选项,例如向文本添加填充或边距,但这只会使按钮变大,似乎并不是最好的方法。
到目前为止,这就是我所拥有的。
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;


为了视觉效果:

React Native

这里是您测试需求的Snack
附注:已经尝试过这个,但没有成功。


您想在图像和文本之间保留一些空间吗? - Nirmalsinh Rathod
@Nirmalsinh 没错!我希望图像靠近左边框,文本位于按钮中间,谢谢! - Franch
请检查我的答案。希望能对您有所帮助。 - Nirmalsinh Rathod
@Nirmalsinh 哇!非常准确!谢谢! - Franch
很高兴能帮助你,伙计。 - Nirmalsinh Rathod
1个回答

6
这里是您的解决方案。更新下面的样式:
对于图标:
icon: {
    transform: [{ rotate: '180deg'}],
    width: 25,
    height: 25,
    position: 'absolute',
    left: 2, // Keep some space between your left border and Image
  },

For Text:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接