React计算文本的高度和宽度

使用场景:项目中需要计算文本的高度,如果超过两行,就折叠文本,显示展示全部按钮

使用span元素来计算,比较准确

    //计算好准确的高度和宽度
    textSize(fontSize, text) {
        let span = document.createElement("span");
        let result = {};
        result.width = span.offsetWidth;
        result.height = span.offsetHeight;
        span.style.visibility = "hidden";
        span.style.fontSize = fontSize;
        span.style.lineHeight = '20px';//最好设置行高 方便项目中计算
        span.style.fontFamily = '-apple-system, "PingFang SC", "Helvetica Neue", Helvetica,\n' +
            'STHeiTi, sans-serif';//字体 可以替换为项目中自己的字体
        span.style.display = "inline-block";
        document.body.appendChild(span);
        if (typeof span.textContent !== "undefined") {
            span.textContent = text;
        } else {
            span.innerText = text;
        }
        result.width = parseFloat(window.getComputedStyle(span).width) - result.width;
        result.height = parseFloat(window.getComputedStyle(span).height) - result.height;
        span.parentNode.removeChild(span);//删除节点
        return result;
    }

更多内容,欢迎同步关注作者公众号二维码!
程序员内功修炼手册 主要发布计算机基础、设计模式、计算机网络基础知识,同时重点关注大前端知识
Android、iOS、web前端、Flutter、React Native等,想学习大前端知识的速度来吧,一起学习、一起成长!
qrcode_for_gh_f730c342ff6e_344.jpg

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React文本编辑框可以使用第三方库来实现,其中比较常用的是`react-quill`和`draft-js`。 1. 使用`react-quill`: 首先,安装`react-quill`库: ``` npm install react-quill ``` 然后,导入必要的组件并创建一个富文本编辑框组件: ```jsx import ReactQuill from 'react-quill'; import 'react-quill/dist/quill.snow.css'; // 导入样式 const RichTextEditor = () => { return ( <ReactQuill theme="snow" /> ); }; export default RichTextEditor; ``` 最后,在你的页面中使用这个组件: ```jsx import React from 'react'; import RichTextEditor from './RichTextEditor'; const App = () => { return ( <div> <h1>React文本编辑框</h1> <RichTextEditor /> </div> ); }; export default App; ``` 2. 使用`draft-js`: 首先,安装`draft-js`库: ``` npm install draft-js ``` 然后,导入必要的组件并创建一个富文本编辑框组件: ```jsx import { Editor, EditorState } from 'draft-js'; import 'draft-js/dist/Draft.css'; // 导入样式 const RichTextEditor = () => { const [editorState, setEditorState] = useState(() => EditorState.createEmpty()); const handleChange = (newEditorState) => { setEditorState(newEditorState); }; return ( <Editor editorState={editorState} onChange={handleChange} /> ); }; export default RichTextEditor; ``` 最后,在你的页面中使用这个组件: ```jsx import React from 'react'; import RichTextEditor from './RichTextEditor'; const App = () => { return ( <div> <h1>React文本编辑框</h1> <RichTextEditor /> </div> ); }; export default App; ``` 以上是两种常见的React文本编辑框的实现方法,你可以根据自己的需求选择适合的库和组件来使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值