import Taro from '@tarojs/taro';
import { View, Text } from '@tarojs/components';
import { ITouchEvent } from '@tarojs/components/types/common';
import _ from 'lodash';
import './index.scss';
interface ILineEllipsis {
text: string;
}
class LineEllipsis extends Taro.Component<ILineEllipsis> {
disabled = false;
state = {
isExpansioned: false,
overflow: false
};
init = () => {
Taro.nextTick(() => {
const query = Taro.createSelectorQuery().in(this.$scope);
query.select(`#text`).boundingClientRect();
query.exec(rect => {
const height = _.get(rect, '0.height', 0);
this.disabled = !(height > 30);
this.setState({
overflow: height > 30
});
});
});
};
componentDidMount() {
this.init();
}
componentWillReceiveProps() {
this.init();
}
handleExpend = (e?: ITouchEvent) => {
e && e.stopPropagation();
this.setState({
overflow: false,
isExpansioned: true
});
};
handleHide = (e?: ITouchEvent) => {
e && e.stopPropagation();
this.setState({
overflow: true,
isExpansioned: false
});
};
toggle = () => {
const { isExpansioned } = this.state;
if (this.disabled) return;
if (isExpansioned) {
this.handleHide();
} else {
this.handleExpend();
}
};
render() {
const { text } = this.props;
const { overflow, isExpansioned } = this.state;
return (
<View
id="wrap"
style={{
position: 'relative',
color: '#999999',
overflow: overflow ? 'hidden' : 'unset',
height: overflow ? '16px' : 'unset',
lineHeight: overflow ? '16px' : 'unset'
}}>
<View id="text" onClick={this.toggle}>
{text}
{!overflow && isExpansioned && (
<Text className="expansion-btn" onClick={this.handleHide}>
收起
</Text>
)}
</View>
{overflow && (
<Text
className="expansion-btn"
onClick={this.handleExpend}
style={{ position: 'absolute', top: '0', right: '0', background: '#fff' }}>
...展开
</Text>
)}
</View>
);
}
}
export default LineEllipsis;