簡體   English   中英

在react-js中的insertAdjacentHTML中添加onclick或eventListener

[英]Add onclick or eventListener in insertAdjacentHTML in react-js

我正在構建一個用於學習目的的簡單 React 應用程序,我剛開始學習 React-js,我試圖在用戶操作上dynamically添加段落並且它運行良好但我想在insertAdjacentHTML (基本上是 innerHTML)中添加一個onClick事件。

但是 onclick 事件在innerHTML中不起作用

應用程序.js

const addParagraph = () => {
    var paragraphSpace = document.getElementById('container')
    paragraphSpace.insertAdjacentHTML('beforeend', `<p>I am dynamically created paragraph for showing purpose<p> <span id="delete-para" onClick={deleteParagraph(this)}>Delete</span>`
}

const deleteParagraph = (e) => {
    document.querySelector(e).parent('div').remove();
}

class App extends React.Component {
    render() {
        return (
            <div>
                <div onClick={addParagraph}>
                     Click here to Add Paragraph
                </div>

                <div id="container"></div>
            </div>
        )
    }
}

我想做什么?

用戶將能夠添加多個段落,我正在嘗試在每個段落上添加一個刪除按鈕,以便用戶可以刪除特定段落

我也嘗試過使用eventListener ,例如:-

const deleteParagraph = () => {
    document.querySelector('#delete').addEventListener("click", "#delete", 
    function(e) {
          e.preventDefault();
          document.querySelector(this).parent('div').remove();
        })
}

但它說

deleteParagraph 未定義

我還嘗試將deleteParagraph包裝在componentDidMount()中,但它會刪除 window 中的所有內容。

任何幫助將非常感激。 謝謝你。

insertAdjecentHTML 不應在 javascripts 框架中使用,因為它們在完全不同的范例上工作。 每次更改組件 state 時,React 組件都會重新渲染。因此,您想通過更改其 state 來操縱組件的外觀

解決方案:在構造函數中初始化組件的 state,稍后您將在單擊按鈕時更改它。 初始 state 是空段落數組。

constructor() {
    super()
    this.state = {
      paragraphs:[]
    }
  }

並在單擊按鈕時更改 state - 如下所示:

<div onClick={addParagraph}>

添加段落 function

const addParagraph = () =>{
   this.state = this.state.push('New paragraph')
}

渲染段落

<div id="container">
this.state.paragraphs.map(paragraph =>{
   <p>{paragraph}</p>
})
</div>

2022 年 ReactJS 的附加提示 - 使用功能組件而不是 Class 組件

不要直接操作 DOM,而是讓 React 處理 DOM 變化。 這是正確實施它的一種方法。

class App extends React.Component {
  state = { paragraphs: [] };

  addParagraph = () => {
    // do not mutate the state directly, make a clone
    const newParagraphs = this.state.paragraphs.slice(0);

    // and mutate the clone, add a new paragraph
    newParagraphs.push('I am dynamically created paragraph for showing purpose');

    // then update the paragraphs in the state
    this.setState({ paragraphs: newParagraphs });
  };

  deleteParagraph = (index) => () => {
    // do not mutate the state directly, make a clone
    const newParagraphs = this.state.paragraphs.slice(0);

    // and mutate the clone, delete the current paragraph
    newParagraphs.splice(index, 1);

    // then update the paragraphs in the state
    this.setState({ paragraphs: newParagraphs });
  };

  render() {
    return (
      <div>
        <div onClick={this.addParagraph}>Click here to Add Paragraph</div>
        <div id="container">
          {this.state.paragraphs.map((paragraph, index) => (
            <>
              <p>{paragraph}</p>
              <span onClick={this.deleteParagraph(index)}>Delete</span>
            </>
          ))}
        </div>
      </div>
    );
  }
}

暫無
暫無

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

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