javascript - ReactJs - 将实用函数传递给模态内的段落

标签 javascript reactjs

我有一个实用函数 noMoreLonelyWords(),它呈现的文本避免在行尾出现一个单词。当我在组件中导入并使用此功能时,一切正常。问题是这个函数没有在模态中渲染段落。我该如何解决?

react 组件:

import React, { Component } from 'react'
import Modal from 'react-responsive-modal';
import { noMoreLonelyWords } from './utilities/utilities.js';

class PortfolioPage extends Component {
    componentDidUpdate() {
        noMoreLonelyWords("p", 2)
    }
    render() {
        return (
            <Modal>
                <p>My text here!</p>
            </Modal>
        )

    }
}

export default PortfolioPage

noMoreLonelyWords 函数: 注意:此功能运行良好。这个函数的主体并不重要。它可以是任何改变段落的东西。目标是将其应用到模态中并修改其段落。

export const noMoreLonelyWords = (selector, numWords) => {      
    var elems = document.querySelectorAll(selector);
    var i;
    for (i = 0; i < elems.length; ++i) { 
      var textArray = elems[i].innerText.split(" ");      
      var lastWords = textArray.splice(-numWords, numWords).join("&nbsp;");     
      var textMinusLastWords = textArray.join(" ");
      elems[i].innerHTML = textMinusLastWords + " " + lastWords;
    }
  }

最佳答案

没有改变状态的 Action 。所以 componentDidUpdate() 从未调用过。

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

这里是文档:https://reactjs.org/docs/react-component.html#componentdidupdate

你应该使用componentDidMount()

componentDidMount(){
    noMoreLonelyWords("p", 2)
}

关于javascript - ReactJs - 将实用函数传递给模态内的段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56471945/

相关文章:

javascript - 将 Div 内容复制到 Textarea 或具有相同 font-family 样式的文本

javascript - 如何使用自定义 Hook 访问结构对象以将背景图像添加到 Canvas ?

javascript - 添加类后如何保持 HTML 元素摇晃/移动

javascript - PrototypeJs 中的 $$ 和 $

reactjs - 尝试使用 React-SearchKit 连接到 ElasticSearch 7 时出现错误 405(方法不允许)

javascript - 在 React 中使用 HTML/CSS 渲染电子邮件

javascript - 即使设置为自动对焦,文本区域也不会自动对焦

javascript - ReactJS/JavaScript 在对象中查找数组

javascript - 在 Suitescript 中,我尝试使用 nlobjFilter 和日期时间变量按分钟过滤记录。有人有这方面的经验吗?

javascript - 表单数据不会使用 onChange() 绑定(bind)到 React 组件