gpt4 book ai didi

javascript - react native : Error while using built-in button

转载 作者:行者123 更新时间:2023-12-01 01:34:58 33 4
gpt4 key购买 nike

我正在尝试学习 React Native,当示例应用程序运行时,我在使用 Button 组件时收到错误。在我的 Android Lollipop 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 Code 中不会显示任何错误。

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 = () => {} 后,问题就解决了。有人能解释一下为什么吗? (我是 React 和 React Native 的新手)

最佳答案

如果你想在没有箭头功能的情况下使用它,你可以绑定(bind)你的函数。

例如。

constructor(props) {
super(props);

// This binding is necessary to make `this` work in the callback
this._startGame = this._startGame.bind(this);
}

_startGame() {
// Do something
}

为什么?

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without () after it, such as onClick={this.handleClick}, you should bind that method.

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

关于javascript - react native : Error while using built-in button,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52913982/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com