也许我的问题不匹配。如何使用另一个组件更改变量的值?我想使用 react-hooks 来更改像 redux 这样的值。 例如,我有变量const [message, setMessage] = useState('');
,该位置SearchScreen.js
文件中。我想更改Test.js
文件中此变量的值。
//SearchScreen file
import 'react-native-gesture-handler'
import React,{ useState } from 'react';
import {View, Text, Button} from 'react-native';
const SearchScreen = ({navigation}) =>{
const [message, setMessage] = useState('');
return(
<View>
<Text>{message}</Text>
<Button
title='enter to next bar'
onPress={() => navigation.navigate('Test')}
/>
</View>
);
};
export default SearchScreen;
和另一个文件
//Test file
import React,{useState} from 'react';
import {View, Text} from 'react-native';
const Test = () =>{
return(
<View>
<Text>
</Text>
</View>
);
};
export default Test;
我可以立即setMessage('Testing')
写入Test.js
文件
通过导航发送 setMessage 值消息的回调
import React,{ useState } from 'react';
import {View, Text, Button} from 'react-native';
const SearchScreen = ({navigation}) =>{
const [message, setMessage] = useState('');
return(
<View>
<Text>{message}</Text>
<Button
title='enter to next bar'
onPress={() => navigation.navigate('Test',{setMessage})}
/>
</View>
);
};
export default SearchScreen;
之后从导航道具中获取此回调,例如在测试路线中
测试文件
import React,{useState} from 'react';
import {View, Text} from 'react-native';
const Test = (props) =>{
const {navigation} = props;
const setMessage = navigation.state.params.setMessage;
return(
<View>
<Text>
</Text>
</View>
);
};
export default Test;
对于文档,请检查将值发送到其他屏幕