1

当在反应中找到模式时,我试图在文本之间添加一个按钮标签,这是在 dangerouslySetInnerHTML 属性中完成的。onClick 仅适用于 alert() 和 console.log(),当我将函数传递给它时它不起作用。我错过了什么?

    export const detectHashTagPattern = (text) => {
      if(!text) return '';
      let pattern = /This is a follow-up to your previous request #[0-9]+/gi;
      let hashTagPattern = /#[0-9]+/;
    
      text = text.replace(pattern, (res) => {
        return res.replace(hashTagPattern, `<button onClick={}>${hashTagPattern.exec(res)}</button>`);
      });

  return text;
};
4

1 回答 1

0

那么你可以像下面这样改变算法:


function clickHandler() {
  console.log("do something");
}

window.clickHandler = clickHandler;

export const detectHashTagPattern = (text) => {
  if (!text) return "";
  let pattern = /This is a follow-up to your previous request #[0-9]+/gi;
  let hashTagPattern = /#[0-9]+/;

  text = text.replace(pattern, (res) => {
    return res.replace(
      hashTagPattern,
      // use window.<fct>()
      `<button onClick="window.${window.clickHandler.name}()">${hashTagPattern.exec(
        res
      )}</button>`
    );
  });

  return text;
};

您不应该采用这种方法,因为它可能在您的应用程序中呈现其他问题(取决于您在处理程序中执行的操作)。

更好的方法是这样的:

const splitSubject = (text) => {
  if (!text) {
    return [""];
  }

  let pattern = /This is a follow-up to your previous request #[0-9]+/gi;

  if (!pattern.test(text)) {
    return [text];
  }
  let hashTagPattern = /#[0-9]+/;
  let result = text.search(hashTagPattern);
  return [text.slice(0, result), text.slice(result), text.slice(result + 1)];
};

const Subject = ({ subject, handler }) => {
  const splitted = splitSubject(subject);

  let content = null;
  if (splitted.length === 1) {
    content = <span>{splitted[0]}</span>;
  } else {
    let [info, cmd, reqReference] = splitted;

    content = (
      <>
        <span>{info}</span>
        <button onClick={() => handler?.(reqReference)}>{cmd}</button>
      </>
    );
  }

  return <p>{content}</p>;
};

export default function App() {
  const requestHandler = (num) => {
    console.log(`click on '${num}'`);
  };

  return (
    <div>
      <Subject
        handler={requestHandler}
        subject="This is a follow-up to your previous request #9"
      />
      <Subject handler={requestHandler} subject="Not matching subject" />
    </div>
  );
}


于 2021-03-28T11:23:39.020 回答