Как передать реквизит с помощью styled-компонентов - PullRequest
0 голосов
/ 21 апреля 2019

Я только недавно начал работать со стилизованными компонентами, и мне интересно, как я мог бы адаптировать этот вид кода, чтобы соответствовать им.То, что я хотел бы сделать, это иметь поведение по умолчанию в моем компоненте AppText.js, но я мог бы перезаписать его компонентами.Возможно, мне придется изменить свой взгляд на вещи, но я совершенно уверен, что с этой библиотекой есть чистое решение.Вот как это выглядит в моем реальном коде.

AppText.js

type Props = {
  children?: React.Node,
  onPress?: Function,
  style?: StyleSheet.Styles,
  textStyle?: StyleSheet.Styles,
}

const AppText = ({ children, onPress, style, textStyle }: Props) => {
  if (!children) {
    return null
  }

  return (
    <View style={{ ...styles.appTextView, ...style }}>
      <Text onPress={onPress} style={{ ...styles.textLabel, ...textStyle }}>
        {children}
      </Text>
    </View>
  )
}

AppText.defaultProps = {
  children: null,
  onPress: () => {},
  style: {},
  textStyle: {},
}

Использование

<AppText
  onPress={() => navigation.goBack()}
  style={styles.cancel}
  textStyle={styles.cancelText}
>
  Retour
</AppText>

1 Ответ

0 голосов
/ 22 апреля 2019

Я наконец-то нашел ответ сам, в конце концов это было довольно легко.Для справки вот мой код.

App.js

/* @flow */
import React from 'react'
import styled from 'styled-components/native'

import MyText from '@components/MyText'

const App = () => (
  <Container>
    <Welcome>Welcome to React Native!</Welcome>
    <Instructions>To get started, edit App.js</Instructions>
    <Instructions>{instructions}</Instructions>
    <MyStyledText
      onPress={() => {
        alert('You clicked this text!')
      }}
    >
      Press here
    </MyStyledText>
  </Container>
)

// Styles
const MyStyledText = styled(MyText)`
  background-color: red
`

export { App as default }

MyText.js

/* @flow */
import type { Node } from 'react'
import React from 'react'
import styled from 'styled-components/native'

// Styles
const StyledText = styled.Text`
  background-color: ${({ style }) => style.backgroundColor || 'blue'};
  font-size: ${({ style }) => style.fontSize || 50};
`

type MyTextProps = {
  children: Node,
  onPress?: Function,
  style?: Object,
}

// My component renders with a background-color of red and a font-size of 50!
const MyText = ({ children, onPress, style }: MyTextProps) => (
  <StyledText onPress={onPress} style={style}>
    {children}
  </StyledText>
)

MyText.defaultProps = {
  onPress: () => {},
  style: {},
}

export { MyText as default }
...