如何使用样式组件传递道具

问题描述 投票:-1回答:1

我刚开始使用样式化组件,我想知道如何调整这种代码以符合它们。我想要做的是在我的组件AppText.js中有一个默认行为,但我可以用组件props覆盖。我可能不得不改变我看待事物的方式,但我很确定这个库有一个干净的解决方案。这就是我实际代码中的样子。

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>
reactjs react-native flowtype styled-components
1个回答
0
投票

我终于找到了自己的答案,最后很容易。作为参考,这是我的代码。

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 }
© www.soinside.com 2019 - 2024. All rights reserved.