gpt4 book ai didi

react-native - undefined 不是对象(评估 '_this.refs.toast.show' )

转载 作者:行者123 更新时间:2023-12-05 07:33:35 24 4
gpt4 key购买 nike

我的目标是监听Android homeback按钮的事件,然后在连续点击时 toast 。这里使用了第三个组件“react-native-easy-toast”,完整代码片段如下:

import React, { Component } from 'react';
import {View, WebView, Platform, BackHandler, StyleSheet} from 'react-native';
import Toast, {DURATION} from 'react-native-easy-toast';

export default class HomeScreen extends Component {
constructor (props) {
super(props);
}

onNavigationStateChange = (event) => {
this.setState({
navCanGoBack : event.canGoBack,
});
};

componentDidMount() {
if (Platform.OS === 'android') {
BackHandler.addEventListener('hardwareBackPress', this.onHomeBackPress);
}
}


onHomeBackPress = () => {
if (this.state.navCanGoBack) {
this.refs['webview'].goBack();
return true;
} else {
//exit app if exceed 2 seconds
if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
return false;
}
this.lastBackPressed = Date.now();
this.refs.toast.show('weill exit app press again');
return true;
}
};

render() {
return (
<View style={{flex:1}}>
<WebView
source={{ uri: 'http://www.test.com/' }}
style={{ width: '100%', height: '100%' }}
ref="webview"
onNavigationStateChange={this.onNavigationStateChange}
/>

<Toast ref="toast" />
</View>
);
}
}

最后,运行应用程序并给出错误:

undefined is not an object(evaluating '_this.refs.toast.show')

我是 React Native 的新手。

最佳答案

请试试

//inside constructor
this.toastRef = React.createRef();

...

<Toast ref={this.toastRef} />

并替换

this.refs.toast.show('weill exit app press again');

this.toastRef.current.show('weill exit app press again');

关于react-native - undefined 不是对象(评估 '_this.refs.toast.show' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50549025/

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