React Native:undefined 不是一个对象
React Native : undefined is not an object
我目前正在学习 React Native。
我只是构建了一个非常简单的应用程序来测试 Button 组件。
当我单击按钮组件时,控制台日志按预期打印。
但是在打印出控制台日志后,它弹出以下错误。
**undefined is not an object (evaluating '_this2.btnPress().bind')**
我不确定哪里出了问题?
谁能告诉我我做错了什么?
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default class App extends React.Component {
btnPress() {
console.log("Fn Button pressed");
}
render() {
return (
<View style={styles.container}>
<Button title="this is a test"
onPress={()=> this.btnPress().bind(this)} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
您正在调用函数而不是通过 bind
传递引用。
松开 ()
.
而且你不应该用箭头函数将它包装为 bind is already returning a new function instance
onPress={this.btnPress.bind(this)} />
顺便说一句,这将 return 并在每个渲染器上创建一个函数实例,您应该在 constructor
中执行一次(仅运行一次):
export default class App extends React.Component {
constructor(props){
super(props);
this.btnPress = this.btnPress.bind(this);
}
btnPress() {
console.log("Fn Button pressed");
}
render() {
return (
<View style={styles.container}>
<Button title="this is a test"
onPress={this.btnPress} />
</View>
);
}
}
或者使用箭头函数,它使用 this
的词法上下文:
export default class App extends React.Component {
btnPress = () => {
console.log("Fn Button pressed");
}
render() {
return (
<View style={styles.container}>
<Button title="this is a test"
onPress={this.btnPress} />
</View>
);
}
}
我目前正在学习 React Native。
我只是构建了一个非常简单的应用程序来测试 Button 组件。
当我单击按钮组件时,控制台日志按预期打印。 但是在打印出控制台日志后,它弹出以下错误。
**undefined is not an object (evaluating '_this2.btnPress().bind')**
我不确定哪里出了问题?
谁能告诉我我做错了什么?
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default class App extends React.Component {
btnPress() {
console.log("Fn Button pressed");
}
render() {
return (
<View style={styles.container}>
<Button title="this is a test"
onPress={()=> this.btnPress().bind(this)} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
您正在调用函数而不是通过 bind
传递引用。
松开 ()
.
而且你不应该用箭头函数将它包装为 bind is already returning a new function instance
onPress={this.btnPress.bind(this)} />
顺便说一句,这将 return 并在每个渲染器上创建一个函数实例,您应该在 constructor
中执行一次(仅运行一次):
export default class App extends React.Component {
constructor(props){
super(props);
this.btnPress = this.btnPress.bind(this);
}
btnPress() {
console.log("Fn Button pressed");
}
render() {
return (
<View style={styles.container}>
<Button title="this is a test"
onPress={this.btnPress} />
</View>
);
}
}
或者使用箭头函数,它使用 this
的词法上下文:
export default class App extends React.Component {
btnPress = () => {
console.log("Fn Button pressed");
}
render() {
return (
<View style={styles.container}>
<Button title="this is a test"
onPress={this.btnPress} />
</View>
);
}
}