如何在React Native中添加按钮?

46

我对“无CSS”这个概念感到困惑,但我理解它的好处。我只想在屏幕中央放置一个按钮,但我还不理解React中的样式如何工作。这是我的代码:

var tapSpeed = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Tap me as fast as you can!
        </Text>
        <View style={styles.button}>
        !
        </View>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFCCCC'
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10
  },
  button: {
    textAlign: 'center',
    color: '#ffffff',
    marginBottom: 7,
    border: 1px solid blue,
    borderRadius: 2px
  }
});

在编辑之前有一些错误的分号和额外的逗号--我认为那些只是打字错误。如果不是,你可能需要检查一下。 - Austin Greco
这不是打错了,但还是谢谢你。然而,我复制粘贴了编辑后的代码,模拟器报错了(屏幕变成了红色)。还有其他想法吗? - baristaGeek
啊,边框应该加上引号:border: '1px solid blue', - Austin Greco
你能把按钮边距都设置为“auto”吗?(我还没怎么用过React Native) - Brigand
@FakeRainBrigand,您不能将按钮边距设置为自动。如果您想要按钮拉伸包裹它们,请在提供的示例中将 lineItems 属性值更改为 'stretch' - vhs
为什么这个没有附带一个按钮!?!? - Alper
9个回答

36

更新: 使用内置的Button组件

已弃用:

在iOS中包装您的视图到TouchableHighlight中,而在Android中使用TouchableNativeFeedback

var {
  Platform,
  TouchableHighlight,
  TouchableNativeFeedback 
} = React;

var tapSpeed = React.createClass({
  buttonClicked: function() {
    console.log('button clicked');
  },
  render: function() {
    var TouchableElement = TouchableHighlight;
    if (Platform.OS === 'android') {
     TouchableElement = TouchableNativeFeedback;
    }
    return (
    <View style={styles.container}>
      <Text style={styles.welcome}>
        Tap me as fast as you can!
      </Text>
      <TouchableElement
        style={styles.button}
        onPress={this.buttonClicked.bind(this)}>
        <View>
          <Text style={styles.buttonText}>Button!</Text>
        </View>
      </TouchableElement>        
    </View>
    );
  }
});       

在哪里可以看到console.log()的输出? - C.P.
@Chetan 在 Chrome 中通过长按屏幕设置调试,并打开浏览器控制台。 - Yevgen Safronov
FYI,the TouchableNativeFeedback doc says目前它只支持将单个View实例作为子节点。 <Text>必须包含在View中。请编辑您的答案,以便其他人不会犯同样的错误。 - Augustin Riedinger
Augustin是正确的,Text标签必须在View标签内,像这样"<View><Text style={styles.buttonText}>Button!</Text></View>",否则会出现运行时错误"Invariant Violation: RawText Button! must be wrapped in an explicit <Text> component"。 - Ziteng Chen
感谢评论中的提示。请编辑 Android 的答案:<TouchableElement style={styles.button}> <view> <Text style={styles.buttonText}>按钮!</Text> </view> </TouchableElement> - Asaf Maoz
在较新的React版本中,bind()是不必要的。React会给出以下警告:警告:bind():您正在将组件方法绑定到组件。React会以高性能的方式自动完成这个操作,因此您可以安全地移除这个调用。 - Aaron Ash

28

您可以使用内置的React Native Button元素。

import React, { Component } from 'react';
import { StyleSheet, View, Button, Alert, AppRegistry } from 'react-native';

class MainApp extends Component {

_onPress() {
  Alert.alert('on Press!');
 }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.buttonContainer}>
          <Button onPress={this._onPress} title="Hello" color="#FFFFFF" accessibilityLabel="Tap on Me"/>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF'
  },
  buttonContainer: {
    backgroundColor: '#2E9298',
    borderRadius: 10,
    padding: 10,
    shadowColor: '#000000',
    shadowOffset: {
      width: 0,
      height: 3
    },
    shadowRadius: 10,
    shadowOpacity: 0.25
  }
})

AppRegistry.registerComponent('MainApp', () => MainApp);

输入图像描述

点击 这里 查看更多信息。


25

react-native-button包提供了一个像本地按钮一样样式的按钮。使用npm install react-native-button进行安装,然后在您的组件中像下面这样使用它:

var Button = require('react-native-button');

var ExampleComponent = React.createClass({
  render() {
    return (
      <Button
        style={{borderWidth: 1, borderColor: 'blue'}}
        onPress={this._handlePress}>
        Press Me!
      </Button>
    );
  },

  _handlePress(event) {
    console.log('Pressed!');
  },
});

3
你可能需要添加--save,像这样:npm install react-native-button --save - ha404
2
无法工作... 出现了这个错误:Error: Requiring unknown module "react-native-button"。 但是我在使用它之前已经安装了这个包。 - backslash112
2
@backslash112 尝试重新启动打包程序。 - ide
3
在iOS上看起来很自然,但在Android上不是。 - Zsolt Szatmari
1
可以工作,但如果按钮比文本更高,则似乎无法在按钮内垂直居中文本。请参见https://github.com/ide/react-native-button/issues/9。有什么想法吗? - Lane Rettig
显示剩余2条评论

1
<Button
  onPress={onPressLearnMore}
  title="Learn More"
  color="#841584"
  accessibilityLabel="Learn more about this purple button"
/>

1

您有两个选项来实现可触摸组件/按钮以处理用户事件。

关于React Native中的样式设置,您需要了解 Flexbox 布局。请查看此CSS Flexbox文章 https://css-tricks.com/snippets/css/a-guide-to-flexbox/,其中所有规则都适用于React Native,但是您需要将规则大写,例如align-content变为alignContent


1
import React, { Component } from 'react';
import { StyleSheet, View, TouchableOpacity, Text} from 'react-native';
var tapSpeed = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <TouchableOpacity>
          <Text style={styles.welcome}>
            Tap me as fast as you can!
          </Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.button}>
          <Text>!</Text>
        </TouchableOpacity>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    flexDirection: 'column',
    alignItems: 'center',
    backgroundColor: '#FFCCCC'
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
    alignSelf: 'center'
  },
  button: {
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 7,
    border: 1px solid blue,
    borderRadius: 2px
  }
});


1
export default class Login extends React.Component {
  barcodeAction = () => {
    this.props.navigation.navigate('BarCodeScanner')
  }

  cleverTapAction = () => {
    this.props.navigation.navigate('CleverTapApp')
  }
} 

render() {
    return (
      <View style={styles.container}>
        <View style={styles.buttonContainer}>
          <Button
            onPress={this._onPressButton}
            title="Press Me"
          />
        </View>
        <View style={styles.buttonContainer}>
          <Button
            onPress={this._onPressButton}
            title="Press Me"
            color="#841584"
          />
        </View>
        <View style={styles.alternativeLayoutButtonContainer}>
          <Button
            onPress={this._onPressButton}
            title="This looks great!"
          />
          <Button
            onPress={this._onPressButton}
            title="OK!"
            color="#841584"
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 1,
   justifyContent: 'center',
  },
  buttonContainer: {
    margin: 20
  },
  alternativeLayoutButtonContainer: {
    margin: 20,
    flexDirection: 'row',
    justifyContent: 'space-between'
  }
});

enter image description here


0
请查看 React Native 文档 相关按钮的内容。
在应用程序中添加按钮并进行样式设置有多种方法。
您可以使用 Button 标签,并且只能通过 color 属性进行一种样式设置。这种样式在 iOS 和 Android 上的显示方式不同,或者将按钮放置在带有样式的 view 标签中。 <View style={style.buttonViewStyle}> <Button title="Facebook" color="blue" onPress={this.onFacebookPress} /> </View> 同时也可以查看 TouchableOpacity 和 TouchableNativeFeedback 标签。
请参考下面的链接以了解如何在应用程序中添加自定义按钮。

https://js.coach/react-native/react-native-action-button?search=button


0

react-native 包中的 Button 元素不提供内置样式特性。例如,“title”属性默认为大写字母。因此,我使用了另一个包react-native-elements ,它提供了漂亮的按钮元素和不同的样式选项。

您可以在 来自react-native-elements的按钮 上查看更多详细信息


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