简体   繁体   English

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

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

I am building a simple react app for learning purpose, I just started learning react-js, I was trying to add paragraph dynamically on user action and it worked perfectly But I want to add an onClick event in insertAdjacentHTML (basically innerHTML).我正在构建一个用于学习目的的简单 React 应用程序,我刚开始学习 React-js,我试图在用户操作上dynamically添加段落并且它运行良好但我想在insertAdjacentHTML (基本上是 innerHTML)中添加一个onClick事件。

But onclick event is not working in innerHTML但是 onclick 事件在innerHTML中不起作用

app.js应用程序.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>
        )
    }
}

What I am trying to do?我想做什么?

User will be able to add multiple paragraphs and I am trying to add a delete button on every paragraph so user can delete particular paragraph用户将能够添加多个段落,我正在尝试在每个段落上添加一个删除按钮,以便用户可以删除特定段落

I have also tried with eventListener like:-我也尝试过使用eventListener ,例如:-

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

But It said但它说

deleteParagraph is not defined deleteParagraph 未定义

I also tried to wrap deleteParagraph in componentDidMount() But it removes everything from the window.我还尝试将deleteParagraph包装在componentDidMount()中,但它会删除 window 中的所有内容。

Any help would be much Appreciated.任何帮助将非常感激。 Thank You.谢谢你。

insertAdjecentHTML should not be used in javascripts frameworks because they work on entirely different paradigm. insertAdjecentHTML 不应在 javascripts 框架中使用,因为它们在完全不同的范例上工作。 React components are rerendered every time you change a component state. So you want to manipulate look of your component by changing its state每次更改组件 state 时,React 组件都会重新渲染。因此,您想通过更改其 state 来操纵组件的外观

Solution: In constructor initialize your component's state which you will change later on button click.解决方案:在构造函数中初始化组件的 state,稍后您将在单击按钮时更改它。 Initial state is array of empty paragraphs.初始 state 是空段落数组。

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

And alter that state on button click - like this:并在单击按钮时更改 state - 如下所示:

<div onClick={addParagraph}>

Add Paragraph function添加段落 function

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

Rendering paragraphs渲染段落

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

Additional tip for ReactJS in 2022 - use Functional components instead of Class components 2022 年 ReactJS 的附加提示 - 使用功能组件而不是 Class 组件

Do not manipulate the DOM directly, let React handle DOM changes instead.不要直接操作 DOM,而是让 React 处理 DOM 变化。 Here's one way to implement it properly.这是正确实施它的一种方法。

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