我是原生 react 新手。我试图在不使用 onpress in 按钮的情况下获取“Key”。 我只想获得一把“ key ”,以便我可以打开组件。这怎么可能?
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
TextInput,
Button,
View,
AsyncStorage
} from 'react-native';
export default class History extends Component {
constructor(props) {
super(props);
this.state = {
myKey: null
}
}
async getKey() {
try {
const value = await AsyncStorage.getItem('@MySuperStore:key');
this.setState({ myKey: value });
} catch (error) {
console.log("Error retrieving data" + error);
}
}
render() {
return (
<View style={styles.container}>
<Button
style={styles.formButton}
onPress={this.getKey.bind(this)}
title="Get Key"
color="#2196f3"
accessibilityLabel="Get Key"
/>
<Text >
Stored key is = {this.state.myKey}
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
padding: 30,
flex: 1,
backgroundColor: '#F5FCFF',
},
});
我可以通过 onpress 获得 key ,但我想要不通过 onpress。请提出建议。
最佳答案
您可以简单地使用 componentDidMount 获取您的键值。你应该知道,当App运行并到达当前屏幕时,在渲染render函数之前和之后都会调用一系列方法。所以 ComponentDidMount 在调用 render 函数之后出现。因此,由于您只需要显示键值,因此只需按照以下代码操作即可。
constructor(props) {
super(props);
this.state = {
myKey:''
}
}
getKey = async() => {
try {
const value = await AsyncStorage.getItem('@MySuperStore:key');
this.setState({ myKey: value });
} catch (error) {
console.log("Error retrieving data" + error);
}
}
componentDidMount(){
this.getKey();
}
render() {
return (
<View style={styles.container}>
<Button
style={styles.formButton}
onPress={this.getKey.bind(this)}
title="Get Key"
color="#2196f3"
accessibilityLabel="Get Key"
/>
<Text >
Stored key is {this.state.myKey}
</Text>
</View>
)
}
每当调用渲染函数时,此时仍然没有设置键值。因此,this.state.myKey
只是Stored key is
。但之后,一旦调用了 componentDidMount,它就会设置 myKey 值并更改状态。这将触发渲染函数再次渲染所有内容。这将最终在文本组件中显示您的键值,而无需触摸任何按钮。
关于javascript - 不使用 onpress React Native 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53416437/