我刚开始使用react,并且我试图在按钮的onPress方法中运行一个简单的函数,但是当我试图加载按钮所在的页面时,它返回错误"unable to find variable 'test'“
以下是代码
import React from 'react';
import { Layout, Button, Text } from 'react-native-ui-kitten';
export default class Settings extends React.Component {
test(){
fetch('http://192.168.100.160:3000/prenotazioni')
.then(response => response.json())
.then(users => console.warn(users))
}
render(){
return (
<Layout style={{flex: 1, alignItems: 'center', justifyContent: "center"}}>
<Text>Sei nelle Settings</Text>
<Button onPress={test}>MySQL</Button>
</Layout>
);
}
}发布于 2019-10-14 15:39:31
请改用onPress={this.test}。
发布于 2019-10-14 15:39:57
改为添加onPress={this.test}。如下图所示:
import React from 'react';
import { Layout, Button, Text } from 'react-native-ui-kitten';
export default class Settings extends React.Component {
constructor(props) {
super(props);
// This binding is necessary to make `this` work in the callback
this.test = this.test.bind(this);
}
test(){
fetch('http://192.168.100.160:3000/prenotazioni')
.then(response => response.json())
.then(users => console.warn(users))
}
render(){
return (
<Layout style={{flex: 1, alignItems: 'center', justifyContent: "center"}}>
<Text>Sei nelle Settings</Text>
<Button onPress={this.test}>MySQL</Button>
</Layout>
);
}
}https://stackoverflow.com/questions/58372012
复制相似问题