当 span 中的内容超过溢出时,我必须将溢出省略号仅应用于一种类型的元素。
我想做什么?
我有一个元素通知列表。对于一种类型的通知“消息”,我需要为其添加溢出省略号。我尝试了类似下面的方法,但没有用。
class main extends React.Purecomponent {
constructor(props) {
super(props);
this.comment_ref = React.createRef();
}
componentDidMount() {
if (this.props.notification.type === 'comment') {
this.set_overflow_class();
}
}
componentDidUpdate(prevProps) {
if (prevProps.notification.id !== this.props.notification.id &&
this.props.notification.type === 'comment') {
this.set_overflow_class();
}
}
set_overflow_class = () => {
const element = this.comment_ref.current;
console.log("comment ref", element);
if(element.scrollWidth > element.clientWidth) {
element.classList.add('overflowing');
}
};
switch(notification.type) {
case 'uploaded':
return (
<ListItem icon={<Svg/>} text={name +
'created item' + item.name} timestamp={timestamp}>
<div className="image">
<Image
width={70}
height={70}
item_id={item.id}
/>
</div>
</ListItem>
);
case 'comment':
return (
<ListItem icon={<Svg/>} text={name +
'commented item' + item.name} ref={this.comment_ref}
className="span" timestamp= {timestamp}>
</ListItem>
);
function ListItem(props) {
return (
<li className="item">
<div className="details">
{props.icon}
<span ref={props.ref} className={props.className}>{props.text}
</span>
</div>
{props.children}
<Timestamp>{props.timestamp}</Timestamp>
</li>
);
}
但它会抛出一个错误:cannot set scrollwidth of undefined
。似乎无法识别 span 元素。
最佳答案
我通过添加 text-overflow: ellipsis css 规则找到了这个问题的答案。
如下所示,
case 'comment':
return (
<ListItem icon={<Svg/>} text={name +
'commented item' + item.name}
className="additional_details" timestamp= {timestamp}>
</ListItem>
);
函数列表项( Prop ){ 返回 ( {props.icon} {props.text} {props.children} { Prop .时间戳} ); }
.additional_details {
overflow: hidden;
width: 20px;
text-overflow: ellipsis;
}
关于css - 如何使用 CSS 和 React 向元素添加溢出省略号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55632093/