简体   繁体   中英

onClick doesn't work on custom created element

Greetings

I have built a search and every time user types word it renders new checkboxes but new checkboxes don't work like they used to be none of the event listeners work on new checkboxes, when I'm clicking on checkboxes they just don't react, but in old ones, until search will render this they are working normally

      //search in checkbox data
      const checkOptions = (container, value, containerId) => {
        for (let i = 0; i < props.unique[containerId].length; i++) {
          let item = props.unique[containerId][i];
          if (
            props.unique[containerId][i] !== null &&
            props.unique[containerId][i].includes(value)
          ) {
            element = (
              <label
                        onClick={(e) => {e.stopPropagation(); ifAnyChecked(e);}} key={i}>
                        <input onClick={(e) => {tableSearch(e);}} type="checkbox" value={item ? item : "empty"}/>
                        {item && item.length > 28 ? (
                          handleCheckbox(item)
                        ) : (
                          <p>{item}</p>
                        )}
                      </label>
            );
            tempData += ReactDOMServer.renderToString(element);
          }
        }
        container.innerHTML = tempData;
      };

any idea what's happening?

Have you tried to use onChange event instead of onClick ? As far as I know, input type checkbox doesn't have such an event like onClick .

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox

I used to get this problem when I was working with Vanilla JS whenever i render a new element then that element was not triggering my events. That was because they were generated on runtime so the event wasn't bound to that element. Now I think that thing is happening here as well. So I changed your code and put it inside a state now it is working. I hope I helped. Do let me know if this is not the solution that you were looking for but it solves your problem though

I put the html inside a state array then i mapped it out inside the newCheckBox div. I changed the input to controlled input with fieldValue state. Lastly i changed the new checkbox alert from onClick={alert("doesn't goes in")} to onClick={() => alert("I think its working now right?")}

Here is the complete code sandbox https://codesandbox.io/s/polished-sea-vedvh?file=/src/App.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM