下面这个方法是在RN使用全局数据共享的,使用原生React的方式搞得,相对于Redux配置相对简单,适合小型项目
项目内创建MyContext.js
// MyContext.js
import React from 'react';
const MyContext = React.createContext();
export default MyContext;
App.js引入
// App.js
import React, { useState } from 'react';
import MyContext from './MyContext';
import ChildComponent from './ChildComponent';
function App() {
// 多个数据的话使用对象包裹
const [globalData, setGlobalData] = useState({
message: 'Hello from Context!',
count: 0
});
// 修改文字
const updateMessage = (newMessage) => {
setGlobalData({ ...globalData, message: newMessage });
};
// 点击将count+1
const incrementCount = () => {
setGlobalData({ ...globalData, count: globalData.count + 1 });
};
// 点击将count-1
const decrementCount = () => {
setGlobalData({ ...globalData, count: globalData.count - 1 });
};
return (
// 多个方法的话,可以往后继续写
<MyContext.Provider value={{ data: globalData, updateMessage, incrementCount, decrementCount }}>
<ChildComponent />
</MyContext.Provider>
);
}
export default App;
组件内使用
// ChildComponent.js
import React, {useContext} from 'react';
import MyContext from './MyContext';
import {Button, SafeAreaView, Text, View} from 'react-native';
function ChildComponent() {
const {data, updateMessage, incrementCount, decrementCount} = useContext(MyContext);
// 修改文字
const handleClick = () => {
updateMessage('New message from ChildComponent!');
};
return (
<SafeAreaView>
<View>
<Text>{data.message}</Text>
<Text>{data.count}</Text>
<Button title="点击修改文字" onPress={handleClick}></Button>
<Button title="点击将count+1" onPress={incrementCount}></Button>
<Button title="点击将count-1" onPress={decrementCount}></Button>
</View>
</SafeAreaView>
);
}
export default ChildComponent;
效果图