coleava / me

1 stars 0 forks source link

小程序之tarojs框架实现文字头像demo #25

Open coleava opened 2 years ago

coleava commented 2 years ago

import { PureComponent } from 'react'
import { View } from '@tarojs/components'
import { map, slice, isArray } from 'lodash'
export default class Avatar extends PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            users: this.props.users,
        }
        this.colors = ['#28CD41', '#AF52DE', '#FF9500', '#007AFF'];
    }

    curtate = (i = 1) => { // 取整
        let index = Math.floor(Math.random() * this.colors.length)
        return this.colors[i || index]
    }

    render() {
        let avatarStyle = Object.assign({}, {
            backgroundColor: `${this.curtate()}`, height: '48px', width: '48px', borderRadius: '48px', color: '#fff', textAlign: 'center', lineHeight: '48px', fontSize: '14px', border: '2px solid #FFFFFF'
        }, this.props.avatarStyle || {})
        const { users } = this.props;

        return <View style={{ display: 'flex', ...this.props.style }}>

            {
                isArray(users) ?
                    (
                        users.length > 0 ? <>
                            {
                                map(slice(users, 0, 3), (user, index) => {
                                    return <View
                                        key={user.id}
                                        style={{ marginLeft: `${index === 0 ? 0 : '-25px'}`, ...avatarStyle }}>
                                        {user.name.substr(user.name.length - 2)}
                                    </View>
                                })
                            }
                            {
                                users.length > 3 && <View style={{ marginLeft: '-25px', ...avatarStyle }}>
                                    +{users.length - 3}
                                </View>
                            }
                        </>
                            : <View style={{ backgroundColor: '#DEDEE0', height: '48px', width: '48px', borderRadius: '48px', color: '#7C7C7D', textAlign: 'center', lineHeight: '48px', fontSize: '14px' }}>暂无</View>
                    ) : <View style={{ ...avatarStyle }}>
                        {users.name.substr(users.name.length - 2)}
                    </View>
            }
        </View>
    }
}