簡體   English   中英

ReactJs-將功利函數傳遞給模式內部的段落

[英]ReactJs - Pass a utilitarian function to a paragraph inside of a modal

我有一個實用的noMoreLonelyWords()來呈現文本,避免在行尾出現單個單詞。 當我在組件中導入並使用此功能時,一切工作都很好。 問題在於此功能未在模態內部呈現段落。 我該如何解決?

反應組件:

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;
    }
  }

無法更改狀態。 因此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)
}

我建議將您的功能應用於文本本身,而不是直接查詢dom。 這不是一個好習慣,特別是考慮到無需直接進行DOM操作就可以實現功能的效果。 您訪問DOM的原因是獲取段落的文本,但是您不需要,因為您已經在render函數中擁有了該文本。


  render() {
  return (
    <Modal>
      <h2><p>{noMoreLonelyWords('My text here!', 2)}</p></h2>
    </Modal>
  )
}

正如@AvinKavish提到的那樣,使用componentDidMount()不能持久保留組件的外觀。

您還可以通過更改選擇器的innerHTML來強制操作DOM。 這是非常反模式的,並且違反了使用React的目的。

假設您想使組件更加復雜。 你可能會更新statePortfolioPage通過加入新的項目,或者您已連接到redux和初始化某種action ,在帶來新props到您的組件。 您的組件將使用新數據重新呈現自身,並將其恢復為初始狀態,從而使componentDidMount()中發生的所有事情均無用。 componentDidMount()將不會再次執行。

另外,我敢肯定在組件已掛載之后 ,調用noMoreLonelyWords很可能很奇怪。 這意味着段落已經顯示在屏幕上,然后它們會不規則地移動以適合您的模式。

您真正應該做的是在render時調用noMoreLonelyWords ,因此在用戶看到您的組件時,您的段落已被正確調整。

要解決此問題,您應該更新noMoreLonelyWords() ,而不是傳遞選擇器進行更新,而只是傳遞文本本身。

export const noMoreLonelyWords = (words, numWords) => {
  var textArray = words.split(" ");
  var lastWords = textArray.splice(-numWords, numWords).join("\xa0");
  var textMinusLastWords = textArray.join(" ");
  var newLine = textMinusLastWords + " " + lastWords;
  return newLine;
};

這將保留您已經編寫的許多邏輯,並且也不會影響組件外部的其他元素,這就是您在調用document.querySelectorAll以獲取頁面上的所有內容並對其進行操作時所執行的操作。

現在,我們可以輸入更新后的noMoreLonelyWords()並通過傳入要配置的任何文本體來使用它。

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

class PortfolioPage extends Component {
  state = {
    openModal: false
  };

  handleModal = () => {
    this.setState({
      openModal: !this.state.openModal
    });
  };

  createParagraphs = (paragraph, minWordsPerLine) => {
    return <p>{noMoreLonelyWords(paragraph, minWordsPerLine)}</p>;
  };

  render() {
    return (
      <div>
        {this.createParagraphs(
          "Hello friend. October arrived, spreading a damp chill over the grounds and into the castle. Madam Pomfrey, the nurse, was kept busy by a sudden spate of colds among the staff and students. Her Pepperup potion worked instantly, though it left the drinker smoking at the ears for several hours afterward. Ginny Weasley, who had been looking pale, was bullied into taking some by Percy. The steam pouring from under her vivid hair gave the impression that her whole head was on fire.",
          5
        )}
        <Modal open={this.state.openModal} onClose={this.handleModal}>
          <div>
            {this.createParagraphs(
              "Hello friend. October arrived, spreading a damp chill over the grounds and into the castle. Madam Pomfrey, the nurse, was kept busy by a sudden spate of colds among the staff and students. Her Pepperup potion worked instantly, though it left the drinker smoking at the ears for several hours afterward. Ginny Weasley, who had been looking pale, was bullied into taking some by Percy. The steam pouring from under her vivid hair gave the impression that her whole head was on fire.",
              15
            )}
          </div>
        </Modal>
        <button onClick={this.handleModal}>Open Modal</button>
      </div>
    );
  }
}

在上面,我們定義了一個名為createParagraphs()的函數。 它接受兩個參數,一個文本主體和一個數字 ,該數字表示允許在一行中的最少單詞數。 它將調用noMoreLonelyWords()並將輸出注入<p></p>

在此處查看其運行情況: https : //codesandbox.io/s/modal-setting-minimum-words-per-line-hy7bc

我們將兩次使用此功能:

  1. 在Modal之外,我們調用createParagraphs()傳遞一些文本,並將最小計數設置為5。現在您可以看到最后一行有5個單詞,符合我們的預期。
  2. 在模態內部,我們調用createParagraphs()傳遞相同的文本,並將需求設置為15。現在,模態在最后一行中有15個單詞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM