问题 :
我正在寻找一种干净的方式来在应用了 CSS 省略号的项目上显示标题工具提示。 (在 React 组件中)
我试过的:
我设置了一个 ref,但它直到 componentDidUpdate 才存在,所以在 componentDidUpdate 中我强制更新。 (这需要更多的返工来处理 Prop 更改等,我可能会使用 setState 代替。)这种工作但有很多我觉得 Not Acceptable 警告。
问题:
有没有更优雅的方式来实现这个目标?
半功能 MCVE:
https://codepen.io/anon/pen/mjYzMM
class App extends React.Component {
render() {
return (
<div>
<Test message="Overflow Ellipsis" />
<Test message="Fits" />
</div>
);
}
}
class Test extends React.Component {
constructor(props) {
super(props);
this.element = React.createRef();
}
componentDidMount() {
this.forceUpdate();
}
doesTextFit = () => {
if (!this.element) return false;
if (!this.element.current) return false;
console.log(
"***",
"offsetWidth: ",
this.element.current.offsetWidth,
"scrollWidth:",
this.element.current.scrollWidth,
"doesTextFit?",
this.element.current.scrollWidth <= this.element.current.offsetWidth
);
return this.element.current.scrollWidth <= this.element.current.offsetWidth;
};
render() {
return (
<p
className="collapse"
ref={this.element}
title={this.doesTextFit() ? "it fits!" : "overflow"}
>
{this.props.message}
</p>
);
}
}
ReactDOM.render(<App />, document.getElementById("container"));
.collapse {
width:60px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<div id="container"></div>
最佳答案
因为很多人还在看这个问题。我终于弄清楚了该怎么做。我会尝试在某个时候将其重写为一个工作示例,但这是要点。
// Setup a ref
const labelRef = useRef(null);
// State for tracking if ellipsis is active
const [isEllipsisActive, setIsEllipsisActive] = useState(false);
// Setup a use effect
useEffect(() => {
if(labelRef?.current?.offsetWidth < labelRef?.current?.scrollWidth) {
setIsEllipsisActive(true);
}
}, [labelRef?.current, value, isLoading]); // I was also tracking if the data was loading
// Div you want to check if ellipsis is active
<div ref={labelRef}>{value}</div>
关于javascript - 如果 CSS 省略号在 React 组件中处于事件状态,我如何有条件地显示标题工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51865904/