Restyle 开源项目教程
项目介绍
Restyle 是一个用于在 React Native 中构建 UI 组件的类型强制系统库。它专注于可主题化的 UI 库构建,假设 UI 是建立在一个设计系统之上,该系统至少定义了一组颜色和间距常量。尽管 Restyle 允许任何样式的覆盖,但它保持开发者最有效率的方式是尽量减少一次性值的使用。
项目快速启动
安装
首先,你需要将 Restyle 添加到你的项目中。你可以使用以下命令之一进行安装:
yarn add @shopify/restyle
# 或者
npm install @shopify/restyle
基本使用
以下是一个使用 Restyle 构建的视图示例:
import { createBox, createText, createTheme } from '@shopify/restyle';
const theme = createTheme({
colors: {
primary: 'blue',
background: 'white',
},
spacing: {
s: 8,
m: 16,
l: 24,
xl: 32,
},
breakpoints: {
phone: 0,
tablet: 768,
},
});
const Box = createBox();
const Text = createText();
const App = () => {
return (
<Box backgroundColor="background" padding="m" flex={1}>
<Text variant="header">Hello, Restyle!</Text>
</Box>
);
};
export default App;
应用案例和最佳实践
主题切换
Restyle 支持动态主题切换,以下是一个简单的主题切换示例:
import { ThemeProvider } from '@shopify/restyle';
const darkTheme = createTheme({
colors: {
primary: 'white',
background: 'black',
},
spacing: {
s: 8,
m: 16,
l: 24,
xl: 32,
},
breakpoints: {
phone: 0,
tablet: 768,
},
});
const App = () => {
const [theme, setTheme] = React.useState(defaultTheme);
return (
<ThemeProvider theme={theme}>
<Box backgroundColor="background" padding="m" flex={1}>
<Text variant="header">Hello, Restyle!</Text>
<Button onPress={() => setTheme(theme === defaultTheme ? darkTheme : defaultTheme)}>
Toggle Theme
</Button>
</Box>
</ThemeProvider>
);
};
响应式设计
Restyle 支持响应式设计,可以根据不同的屏幕尺寸应用不同的样式:
const ResponsiveBox = () => {
return (
<Box
backgroundColor="primary"
padding={{ phone: 's', tablet: 'l' }}
width={{ phone: '100%', tablet: '50%' }}
>
<Text>Responsive Box</Text>
</Box>
);
};
典型生态项目
Restyle 与其他库的集成
Restyle 可以与其他流行的 React Native 库集成,例如 React Navigation:
import { createStackNavigator } from '@react-navigation/stack';
import { useTheme } from '@shopify/restyle';
const Stack = createStackNavigator();
const App = () => {
const theme = useTheme();
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: theme.colors.primary,
},
headerTintColor: theme.colors.background,
}}
>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
通过以上示例,你可以看到 Restyle 如何帮助你构建一致且可主题化的 UI,同时与其他生态项目无缝集成。