26

我正在使用react-native-icons包来包含带有按钮的图标。他们在示例文件夹中列出了示例代码。我试图onPress在 View 上实现,但结果 react-native 没有组件onPress功能<View>

我尝试使用<TouchableHighlight>,但它只能有一个子元素,而不是两个喜欢<Icon><Text>里面。

我也尝试使用<Text>with<Icon><Text>inside,但里面<Text>只能有<Text>元素。

有没有人有运气实现类似的功能?

带有图标的示例按钮

<View onPress={this.onBooking} 
  style={styles.button}>
  <Icon
    name='fontawesome|facebook-square'
    size={25}
    color='#3b5998'
    style={{height:25,width:25}}/>
  <Text style={styles.buttonText}>Sign In with Facebook</Text>
</View>
4

3 回答 3

48

如果您使用的是react-native-icons模块,您可以尝试将图标和文本都包装在一个视图中,然后在其上使用 TouchableHighlight。就像是:

<TouchableHighlight onPress={()=>{}}>
     <View>
         <Icon ... />
         <Text ... />
     </View>
 </TouchableHighlight>

但是如果你使用一个相对新的模块react-native-vector-icons会很容易。你可以这样做:

<Icon name="facebook" style={styles.icon}>
   <Text style={styles.text}>Login with Facebook</Text>
</Icon>
于 2015-06-03T19:24:14.807 回答
10

我设法做到了这样。我想知道是否有更好的方法。

var styles = StyleSheet.create({
  btnClickContain: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'stretch',
    alignSelf: 'stretch',
    backgroundColor: '#009D6E',
    borderRadius: 5,
    padding: 5,
    marginTop: 5,
    marginBottom: 5,
  },
  btnContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'stretch',
    alignSelf: 'stretch',
    borderRadius: 10,
  },
  btnIcon: {
    height: 25,
    width: 25,
  },
  btnText: {
    fontSize: 18,
    color: '#FAFAFA',
    marginLeft: 10,
    marginTop: 2,
  }
});

<TouchableHighlight
  onPress={this.onBooking} style={styles.btnClickContain}
  underlayColor='#042417'>
  <View
    style={styles.btnContainer}>
    <Icon
      name='fontawesome|facebook-square'
      size={25}
      color='#042'
      style={styles.btnIcon}/>
    <Text style={styles.btnText}>Sign In with Facebook</Text>
  </View>
</TouchableHighlight>
于 2015-05-26T03:13:01.057 回答
8

Expo一个Button组件可以满足您的需求,样式和所有功能:

<FontAwesome.Button name="facebook" backgroundColor="#3b5998" onPress={...}>
  Sign in with Facebook
</FontAwesome.Button>
<FontAwesome.Button name="twitter" backgroundColor="#1da1f2" onPress={...}>
  Sign in with Twitter
</FontAwesome.Button>

在 iOS 模拟器中运行的样子:

在此处输入图像描述

如果您不使用Expo,请研究源代码并创建一个类似的组件。

于 2019-12-01T11:39:36.003 回答