css - 如何使用 CSS 和 React 向元素添加溢出省略号?

标签 css reactjs

当 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/

相关文章:

javascript - 每个图像 slider 的多组 jQuery

jquery - 响应式导航

javascript - 在Chrome/Firefox开发者工具中,是否可以隐藏除前两个错误以外的所有错误? (由于React提供了很多垃圾错误)

java - ReactJS 客户端无法与 Java Web 服务通信

javascript - 更改 react native map 中事件标记的不透明度

css - 右栏中的文字低于左栏中的图像

html - 具有两列问题的CSS下拉菜单

css - 无法覆盖导航和超大屏幕之间的边距

javascript - React 测试库 : How to find text in the document which is updated by setInterval?

javascript - 我的 react 输入类型 == 数字不起作用