akveo / akveo/react-native-ui-kitten

useStyles hook

Offen
#1,436 3 Kommentare 2 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen
:bulb: Proposal
Vorherrschende Sprache
TypeScript
Sterne
10.7k
Forks
962
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

## 🚀 Feature Proposal

An optional `useStyles('CustomComponent', props)` hook alternative to `styled` HOC/decorator for custom components.

## Motivation

A hook could lead to cleaner api/less typing/less wrapper components in component tree when you inspect...

## Example

I have a somewhat working implementation below. I needed `StyleConsumerService` and `MappingContext` to get it working, but they aren't exported at package level so the direct file imports feel a little brittle since a new version update could change internal structure.

```ts
import { useContext, useState, useMemo } from 'react';
import { useTheme } from '@ui-kitten/components';
import { StyleConsumerService } from '@ui-kitten/components/theme/style/styleConsumer.service';
import { MappingContext } from '@ui-kitten/components/theme/mapping/mappingContext';

export function useStyles

(componentName: string, sourceProps: P): any {
const [interaction, dispatch] = useState([]);
const theme = useTheme();
const mappingContext = useContext(MappingContext);
const service = useMemo(() => new StyleConsumerService(componentName, mappingContext), [
componentName,
mappingContext,
]);
const defaultProps = useMemo(() => service.createDefaultProps(), [service]);
const props = { ...defaultProps, ...sourceProps };
const style = service.createStyleProp(props, mappingContext, theme, interaction);

// return eva object:
return {
theme,
style,
dispatch,
};
}
```

### Usage
```tsx
export const CustomComponent = props => {
// needs the props to determine variants:
const eva = useStyles('CustomComponent', props);
// convert eva mapping token values to style object:
const styles = getComponentStyles(eva.style);

// eva.dispatch([Interaction.HOVER]); possible to change interaction state and trigger rerender styles lookup

return ...;
}

// vs styled hoc:

const CustomComponent = props => {
const evaStyles = props.eva.style;
// convert eva mapping token values to style object:
const styles = getComponentStyles(evaStyles);
return ...;
}
const StyledCustomComponent = styled('CustomComponent')(CustomComponent);
export { StyledCustomComponent as CustomComponent };

```

Beitragsleitfaden

Beitragsleitfaden öffnen

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.