我刚刚创建了两个库(
Theme
和Snackbar
),这些库可以作为独立包安装,但现在我想选择支持某些功能,以防项目安装我的两个库。
例如
应用程序.js
import { SnackbarProvider } from 'myLibrary/snackbar';
import { ThemeProvider } from 'myLibrary/theme';
import React from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import Routes from './Routes';
const App = () => {
return (
<SafeAreaProvider>
<ThemeProvider color={primary:'red'}>
<SnackbarProvider>
<Routes />
</SnackbarProvider>
</ThemeProvider>
</SafeAreaProvider>
);
};
App.displayName = 'App';
export default App;
上面的代码代表使用我的库(
myLibrary/snackbar
和myLibrary/theme
)的项目代码
为了访问项目中的
theme
,我提供了一个名为 useTheme
的钩子。
现在我想增强
myLibrary/snackbar
库来参考 myLibrary/theme
设置,例如颜色、字体等。
如何在
useTheme
内有条件地使用 myLibrary/snackbar
?
Snackbar.js
import React from 'react';
import {View, Text} from 'react-native';
// import { useTheme } from 'myLibrary/theme';
const Snackbar = props => {
// use color from `useTheme` or fallback to default color
// conditionally use hook if exist
// const {color} = useTheme()
return (
<View style={{flex: 1}}>
<Text style={{
color: color
}}>Snackbar Component</Text>
</View>
);
};
export default Snackbar;
你可以简单地做这样的事情:
let useTheme;
async function dynamicLoad ()
{
useTheme = await import('myLibrary/theme')
.then
(
module => module.useTheme
)
.catch
(
issue => console.log(issue.message)
);
jQuery = await import('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js');
// Load any more dynamic stuff here and activate/install
// them in your app/library.
// Optionaly return them.
return {useTheme, jQuery};
};
console.clear();
console.log('Dinamically loading resources... (see in DevTools console)');
dynamicLoad().then
(
dynamicLoaded => console.log('Dinamically Loaded:', dynamicLoaded)
);