Skip to content

Commit

Permalink
feat: button children 样式场景适配
Browse files Browse the repository at this point in the history
  • Loading branch information
WX-DongXing committed Jun 3, 2024
1 parent 095c2d7 commit c7b47e5
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ import {
Easing,
NativeSyntheticEvent,
} from 'react-native'
import { extractTextStyle } from './utils'
import { extractTextStyle, isText, every } from './utils'
import useInnerProps, { getCustomEvent } from './getInnerListeners'
import useNodesRef from '../../useNodesRef'

Expand Down Expand Up @@ -335,6 +335,16 @@ const Button = forwardRef<View, ButtonProps>((props, ref): React.JSX.Element =>
handleOpenTypeEvent(evt)
}

function wrapChildren(children: ReactNode, textStyle?: StyleProp<TextStyle>) {
if (every(children, (child)=>isText(child))) {
children = <Text style={textStyle}>{children}</Text>
} else {
if(textStyle) console.warn('Text style will be ignored unless every child of the button is Text node!')
}

return children
}

const { nodeRef } = useNodesRef(props, ref, {
defaultStyle: StyleSheet.flatten([
...defaultViewStyle,
Expand Down Expand Up @@ -375,13 +385,15 @@ const Button = forwardRef<View, ButtonProps>((props, ref): React.JSX.Element =>
applyHoverEffect && hoverStyle,
]}>
{loading && <Loading alone={!React.Children.count(children)} />}
<Text
style={[
...defaultTextStyle,
applyHoverEffect && textHoverStyle,
]}>
{children}
</Text>
{
wrapChildren(
children,
[
...defaultTextStyle,
applyHoverEffect && textHoverStyle,
]
)
}
</View>
)
})
Expand Down
11 changes: 10 additions & 1 deletion packages/webpack-plugin/lib/runtime/components/react/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useRef, Children, ReactElement, FunctionComponent } from 'react'
import { useEffect, useRef, Children, ReactElement, FunctionComponent, ReactNode } from 'react'
import { StyleProp, StyleSheet, TextStyle, ViewStyle } from 'react-native'

const TEXT_STYLE_REGEX = /color|font.*|text.*|letterSpacing|lineHeight|includeFontPadding|writingDirection/
Expand Down Expand Up @@ -80,3 +80,12 @@ export const getRestProps = (transferProps: any = {}, originProps: any = {}, del
...omit(originProps, deletePropsKey)
}
}

export const isText = (ele: ReactNode) => {
const displayName = ele?.type?.displayName
return displayName === 'mpx-text' || displayName === 'Text'
}

export function every(children: ReactNode, callback: (children: ReactNode) => boolean ) {
return Children.toArray(children).every((child) => callback(child as ReactNode))
}

0 comments on commit c7b47e5

Please sign in to comment.