gpt4 book ai didi

javascript - 从不同组件获取功能时遇到问题

转载 作者:行者123 更新时间:2023-12-03 00:41:11 25 4
gpt4 key购买 nike

我是原生 react 新手。我正在尝试从不同的组件获取“ key ”。我的意思是我试图从不同的组件(作为父组件)调用函数。但是,我对所有这些引用电话之类的事情完全感到困惑。请向我建议如何从不同的组件调用函数。

// AddScreen.js

import React, { Component } from 'react';
import { AppRegistry, AsyncStorage, View, Text, Button, TextInput, StyleSheet, Image, TouchableHighlight, Linking } from 'react-native';
import styles from '../components/styles';
import { createStackNavigator } from 'react-navigation';
import History from '../components/History';

export default class AddScreen extends Component {
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);
}
}
async saveKey(value) {
try {
await AsyncStorage.setItem('@MySuperStore:key', value);
} catch (error) {
console.log("Error saving data" + error);
}
}
componentDidMount() {
this.getKey();
}
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.MainContainer}>
<View style={styles.Date_input}>
<TextInput
placeholder="Add input"
value={this.state.myKey}
onChangeText={(value) => this.saveKey(value)}
/>
</View>
<View style={styles.getKeytext}>
<Text >
Stored key is = {this.state.myKey}
</Text>
</View>
<View style={styles.Historybutton}>
<Button
onPress={() => navigate('History')}
title="Press Me"
/>
</View>
</View>
)
}
}

//History.js

import React, { Component } from 'react';
import AddScreen from '../components/AddScreen';
import {
AppRegistry,
StyleSheet,
Text,
TextInput,
Button,
View,
AsyncStorage
} from 'react-native';

export default class History extends Component {
constructor(props) {
super(props);
this.state = {
myKey: ''
}

}
render() {call async function synchronously
return (
<View style={styles.container}>
<Button
style={styles.formButton}
onPress={this.onClick}
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',
},
});

我只想从 History 组件调用 getKey 函数来获取 History 上的 myKey 值> 组件的屏幕。

请以我的组件为例向我提出建议。

最佳答案

您只需通过导航参数传递 key 即可。

<Button
onPress={() => navigate('History', { key: this.state.myKey })}
title="Press Me"
/>

在你的历史组件中你可以这样做

render() {
const key = this.props.navigation.getParam('key');

return (
// other code
)
}

您可以在此处阅读有关传递参数的更多信息。 https://reactnavigation.org/docs/en/params.html

关于javascript - 从不同组件获取功能时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53456429/

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