也许我的问题不匹配。如何使用其他组件更改变量的值?我想使用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
答案 0 :(得分:1)
通过导航发送回叫以获取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;
有关文档的检查,send value to other screen