@fluentui- react-native/use-tokes (英语)
此套件提供了创建钩子函数的手段来从被传递的主题中构建出一组令牌,以及给定钩子函数和主题的配对独有的缓存对象. 这些已解析的符号应该用来为您的组件构建样式 。 这样,一个组件的外观和感觉就可以从常量,主题全局,甚至组件特定覆盖来建立起来.
键
一个符号仅仅是一个显示组件样式的设置. 这些可以被认为是框架自动所建的附加组件道具. 通常设定在组件创建时间或被一个主题所覆盖,但可以从多种来源获得:
- 对象 - 这是一个对象内包含的一组值。 假设这些值在物体的寿命期间保持不变.
- 主题函数 - 允许在一个主题中设定与值相关的值。 一个例子是,在主题中的彩色调色板中为特定条目设置颜色.
- 搜索名称 - 这将查询此组件的符号对象或主题函数的主题 .
实例
该系统的核心思想是: Tokens + Theme ==> Styles。这可以被认为是:
- 您的作风是通过配方制作的,最好通过返回的缓存或使用
useMemo钩子或等同物 - 代币是你的配方
- 其中一些信物来自常数
- 有些信物来自主题
该方法的总体特征如下:
export type StyledTextTokens = Pick<TextProps[style], 'color', 'fontFamily', 'fontWeight', 'fontSize'>;
const useTokens = buildUseTokens<StyledTextTokens, Theme>(
/* function for looking up a component in a theme, allows this to be used independently of the shape of the theme */
getComponentInfoFromTheme,
/* Start of tokens, these are applied in order */
/* object, these are effectively constants to be used as defaults */
{ token1: 'foo', token2: 400 },
/* theme function */
(theme: Theme) => ({ token3: theme.colors.backgroundColor }),
/* name to lookup */
'NameToLookup',
);
这个 useTokens 然后可以使用钩来构建组件的样式如下:
const StyledText: React.FunctionComponent<TextProps> = (props) => {
// split the props
const { style, children, ...rest } = props;
// left out of the hook to allow theme to be obtained in whatever way is appropriate. Generally from a context.
const theme = useTheme();
// get a set of tokens from the theme
const [tokens, cache] = useTokens(theme);
// create a style object from the tokens using the cache. Note that if all the tokens are actually directly styles the tokens could be used
// directly. This is just to illustrate the pattern for a more complex component
const [tokenStyle] = cache(() => ({ ...tokens }), []);
// now merge any styles coming from the props in on top as they should override
const mergedStyles = mergeStyles<TextStyle>(tokenStyle, style);
// now just render the text element
return (
<Text {...rest} style={mergedStyles}>
{children}
</Text>
);
};
层层
这些令牌会按照它们在数组中出现的顺序被深刻地合并.
const mergedTokens = merge(
...options.tokens.map(entry => {
// string gets converted to object or function (or empty object)
if (typeof entry === 'string') {
entry = themeHelper.getComponentInfo(entry) || {};
}
// return either the function call (which will produce an object) or the object
return typeof entry === 'function' ? entry(theme) : entry;
});
);