我最近才刚开始使用样式化的组件,我想知道如何才能使这种代码与它们兼容。我想做的是在组件AppText.js
中具有默认行为,但是我可以用组件prop覆盖它。我可能不得不改变看待事物的方式,但是我很肯定这个库有一个干净的解决方案。这就是我的实际代码中的样子。
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>
答案 0 :(得分: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 }