代码之家  ›  专栏  ›  技术社区  ›  Shukant Pal

react native:使用内置按钮时出错

  •  0
  • Shukant Pal  · 技术社区  · 6 年前

    我正在尝试学习本地的react,当示例应用程序工作时,我在使用按钮组件时会得到一个错误。错误出现在我的安卓棒棒糖5.1智能手机的正常红色背景中。

    java.lang.String cannot be cast to
    com.facebook.react.uimanager.AccessiblityDelegate$AccessibilityRole
    
    setDelegate
    AccessbilityDelegateUtil.java:93
    
    updateViewAccessibility
    BaseViewManager.java:260
    
    // and more stack trace was given
    

    App.js 包含以下代码,这些代码在VS代码中不显示任何错误。

    import React, {Component} from 'react';
    import {Platform, StyleSheet, Text, View, Button} from 'react-native';
    
    const instructions = Platform.select({
      ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
      android:
        'This was edited by Shukant Pal for testing',
    });
    
    type Props = {};
    export default class App extends Component<Props> {
    _startGame = () => {
    
    }
    
    _loadExistingGame = () => {
    
    }
    
    _loadTemplateLibrary = () => {
    
    }
    
    _displayAboutUs = () => {
    
    }
    
    render() {
      return (
        <View style={styles.container}>
          <Text>This works</Text>
          <View style={styles.container}>
            <Button onPress={this._startGame} title="New Game" />
          </View>
        </View>
      );
    }
    }
    
    const styles = StyleSheet.create({
     container: {
       flex: 1,
       justifyContent: 'center',
       alignItems: 'center',
       backgroundColor: '#F5FCFF',
      },
      welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
      },
      instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
      },
    });
    

    在发布此问题之前,我进行了以下检查:

    1. 从react native导入按钮

    2. 以前 onPress={this._startGame} 给错了。在将方法声明从 name() name = () => {} 解决了。有人能解释为什么吗?(我是新来的反应和反应本地人)

    2 回复  |  直到 6 年前
        1
  •  1
  •   Jeff Gu Kang    6 年前

    如果要在不使用箭头函数的情况下使用函数,可以对其进行绑定。

    例如。

    constructor(props) {
      super(props);
    
      // This binding is necessary to make `this` work in the callback
      this._startGame = this._startGame.bind(this);
    }
    
    _startGame() {
      // Do something
    }
    

    为什么?

    在JSX回调中,您必须注意这一点的含义。在JavaScript中,类方法默认不绑定。如果忘记绑定this.handleclick并将其传递给onclick,那么在实际调用函数时,这将是未定义的。

    这不是特定于反应的行为;它是函数如何在JavaScript中工作的一部分。一般来说,如果引用一个后面没有()的方法,例如onclick=this.handleclick,则应该绑定该方法。

    Official

    您的方法是ES7第2阶段中的类属性 _startGame = () => {} .

    https://borgs.cybrilla.com/tils/es7-class-properties/

    CRNA包括 babel-plugin-proposal-class-properties 用于此语法。这就是我们不需要在babel上附加设置就可以使用语法的方法。

    https://babeljs.io/docs/en/babel-plugin-proposal-class-properties

        2
  •  1
  •   Shegun    6 年前

    因为javascript“this”关键字的工作方式。当在事件监听器上使用“this”时,“this”关键字不再引用类组件,而是引用事件所作用的元素,所以这就是您得到错误的原因。

    看看这篇文章,它给出了这个关键字的详细解释。

    this - Javascript | MDN