gpt4 book ai didi

javascript - 如何仅在文本溢出时显示按钮

转载 作者:行者123 更新时间:2023-12-01 23:21:16 25 4
gpt4 key购买 nike

我有一个组件需要在文本溢出时显示一个按钮。目前我将 text-overflow 设置为 ellipsis 并希望在那之后显示一个按钮。

这变得很复杂,因为没有固定数量的允许字符或特定大小。

无论如何,我如何使用 React 或 SCSS 检查它?

这是我目前拥有的示例:

const content = [
'short string. No button should be displayed.',
'Long string, please display button! Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'
]

const RenderString = ({content}) => {
return (
<div style={{ border: '1px solid blue' }}>
<div className='limited-space'>
{content}
</div>
<button>You should only see me if text is too long</button>
</div>
)
}

const App = () => {

return (
<div>
{content.map((c, index) => <RenderString key={index} content={c}/>)}
</div>
)
}


ReactDOM.render(
<App />,
document.getElementById('app')
);
.limited-space {
margin: 10px;
padding: 10px;
width: 400px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
border: 1px red solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>

最佳答案

来源:this answer

const content = [
'short string. No button should be displayed.',
'Long string, please display button! Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'
]

const RenderString = ({content}) => {
const [isOverflowing, setIsOverflowing] = React.useState(false);
const widthRef = React.useRef(null);

React.useEffect(() => {
const el = widthRef.current;
if(el.offsetWidth < el.scrollWidth){
setIsOverflowing(true);
}
}, []);

return (
<div style={{ border: '1px solid blue' }}>
<div className='limited-space' ref={widthRef}>
{content}
</div>
{isOverflowing ? <button>You should only see me if text is too long</button> : null }
</div>
)
}

const App = () => {

return (
<div>
{content.map((c, index) => <RenderString key={index} content={c}/>)}
</div>
)
}


ReactDOM.render(
<App />,
document.getElementById('app')
);
.limited-space {
margin: 10px;
padding: 10px;
width: 400px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
border: 1px red solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>

关于javascript - 如何仅在文本溢出时显示按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68087644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com