#javascript #reactjs #contenteditable
#язык JavaScript #реагирует на #удовлетворенность
Вопрос:
Я использую пакет react-contentEditable из npm. Когда мой пользователь нажимает на контакт, я хочу показать красивую метку, имя, а также кнопку, чтобы удалить эту метку из редактируемого div, если пользователь хочет.
У меня есть метка и имя, но я, кажется, не могу понять, как передать onClick кнопке, когда она отображается так, как показано ниже
`lt;label contentEditable="false" class="p-1 rounded-capsule"gt;${contact.firstName " " contact.lastName " "}lt;span class="badge fs--1 badge-soft-success badge-pill ml-2"gt;${contact.phone_number}lt;/spangt;lt;button class="badge-pill badge-soft-primary"gt;Xlt;/buttongt;lt;/labelgt;`)) // How do I pass an onClick to the button?
Вот полный компонент
import React, { useState, useRef, useEffect, Fragment } from 'react'; import ContentEditable from 'react-contenteditable'; const [toField, setToField] = useState({value: " ", html: " "}) const toFieldRef = useRef() const addContactsToDiv = () =gt; { let selectedContactsArray = [] // create and empty array const Matches = selectedRows.filter((row) =gt; { const isMatched = contacts.some(contact =gt; { if(contact._id == row) { selectedContactsArray.push({firstName: contact.firstName, lastName: contact.lastName, phone_number:contact.phone_number, _id: contact._id}) }}) return isMatched }) const matchedContactsArray = [] selectedContactsArray.map(contact =gt; { // mapping over selected to add html // How can I add an onClick to the button when I have to pass it as string? matchedContactsArray.push((`lt;label contentEditable="false" class="p-1 font-weight-bold bg-primary ml-2 text-white rounded-capsule shadow-none fs--3"gt;${contact.firstName " " contact.lastName " "}lt;span class="badge fs--1 badge-soft-success badge-pill ml-2"gt;${contact.phone_number}lt;/spangt;lt;button class="badge-pill badge-soft-primary"gt;Xlt;/buttongt;lt;span name="indy-contacts" class="d-none"gt;${contact._id}lt;/spangt;lt;/labelgt;`)) }) matchedContactsArray.map(contact =gt; { return contact}) const stringifiedRows = matchedContactsArray.toString() // push stringified results in to array setToField({...toField, html: stringifiedRows}) // update state with array instead of updating state inside loop } lt;ContentEditable name="to" innerRef={toFieldRef} // passing our ref instead of state html={toField.html} // the html = our ref.current property //value={toField} onBlur={handleBlur} onClick={() =gt; {handleClick()}} onChange={handleChange} // this sets our refs.current = event.target.value style={{minHeight: "7em", maxHeight: "10em", overflow: "auto"}} className="border border-2x border-300 bg-light rounded-soft fs-1" gt; lt;/ContentEditablegt;
// к этой кнопке X нужно добавить один клик