mh-rn-component
Version:
121 lines (117 loc) • 3.51 kB
Flow
import React, { useState, useEffect } from 'react'
import { dp } from '../utils/index';
import { ButtonType } from '../types'
import { View, Text, TouchableOpacity, TouchableWithoutFeedback, StyleProp, ViewStyle, TextStyle, StyleSheet, Platform, Animated } from 'react-native';
import Icon from '../Icon'
type Props = {
type?: 'default' | 'primary' | 'success' | 'warning' | 'danger',
color?: string,
// todo 后续确认一下弹窗的类型
icon?: any,
text?: string,
textStyle?:StyleProp<TextStyle>,
children?: any,
disabled?: boolean,
style?: StyleProp<ViewStyle | TextStyle>,
// todo loading状态的图标要怎么定义?
loading?: boolean,
//* 按钮圆角
borderRadius?: number | string
onPress?: () => void,
plain?:boolean
}
const Button = (props: Props) => {
/**
* type 样式的处理
*/
const [buttonStyle, setButtonStyle] = useState<ViewStyle | TextStyle>({});
const [plainStyle,setPlainStyle] = useState<ViewStyle | TextStyle>({})
const [fontColor, setFontColor] = useState<string>('#333')
const type = props?.type || 'default'
useEffect(() => {
if (type !== 'default') {
setFontColor('#fff')
} else {
setFontColor('#333')
}
}, [props?.type]);
/**
* todo 是否还需要? 处理边框圆角
*/
useEffect(() => {
if (props.borderRadius) {
if (typeof props.borderRadius == 'string') {
setButtonStyle((oldStyles) => ({
...oldStyles,
borderRadius: (styles.button.height / 2)
}))
} else {
setButtonStyle((oldStyles) => ({
...oldStyles,
borderRadius: Number(props.borderRadius)
}))
}
}
}, [])
useEffect(()=>{
if(props.plain){
setPlainStyle({
backgroundColor:"#fff",
color:ButtonType[type],
borderWidth:1,
borderColor:props.color ? props.color : ButtonType[type],
})
props.color && setFontColor(props.color)
}
},[props.plain,props.color])
return (
<Animated.View>
<TouchableWithoutFeedback disabled={props?.disabled}>
<TouchableOpacity onPress={props.onPress} activeOpacity={0.8}>
<View style={StyleSheet.flatten([
styles.button,
styles.content,
styles.plr10,
{ backgroundColor: props.color ? props.color : ButtonType[type] },
(type === 'default' && !props.color) && styles.border,
plainStyle,
props.style,
{ opacity: props?.disabled ? 0.5 : 1,
borderRadius:props.borderRadius && Number(props.borderRadius) || 0,
}
])}>
{
props.icon && (
<Icon color={fontColor} name={props.icon}></Icon>
)
}
<Text style={[styles.content, { color:props.color ? fontColor : props.plain ? ButtonType[type] : fontColor },props.textStyle]}>{props?.children}</Text>
</View>
</TouchableOpacity>
</TouchableWithoutFeedback>
</Animated.View>
)
}
const styles = StyleSheet.create({
button: {
minWidth: dp(88),
height: dp(44),
borderStyle: 'solid',
backgroundColor: '#fff',
...(Platform.OS === 'web' && { cursor: 'pointer' }),
},
content: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
border: {
borderWidth: 1,
borderColor: '#333'
},
plr10:{
paddingLeft:10,
paddingRight:10,
}
});
export default Button