Warm tip: This article is reproduced from stackoverflow.com, please click
javascript reactjs contenteditable

React Contenteditable

发布于 2020-03-29 12:47:13

Is there anyway I can use something like this:

<span onClick={(e) => console.log(e)}>Testing</span>

Inside react-contenteditable to handle the click on Testing keyword?

When I use the html prop, it would only take an html string, something like <span onclick="something()"></span> I suppose, but is there a way to do it in react instead?

And if I use <span onclick="something()"> where should I define this function something()? I suppose at this point I won't have access to the functions defined in react, right? So how should I do this?

Questioner
Ali Elkhateeb
Viewed
22
bamse 2020-02-03 22:46

onClick is a React property so react-contenteditable wouldn't know what to do with it - since html expects plain html

A hacky way to achieve what you want - or pretty close to it - is:

  1. Create an onClickContentEditable function and is it as onClick for ContentEditable
  2. Add an innerRef to ContentEditable
  3. in onClickContentEditable, then the clicked element is ContentEditable do nothing - since we want to interact only with the children of ContentEditable
  4. Based on DOM attributes of the clicked element (tagName, className ...etc) fun with it! :) In onClickContentEditable you can check the DOM attributes of the clicked element and take action accordingly. You could create a class to mark the element you want to click.

You can test this implementation here - the sandbox is forked from the complex react-contenteditable example. I logged the interactions in the console.

Hope it helps!