如何从 jsx 中的 html 符号中检索实际值?

How to retrieve real value from html symbols in jsx?

我有一个简单的 HTML 表单,输入 name="comment"。我正在使用 {formData.comment} 在 React 应用程序中使用 jsx 显示结果。
对于像 hello world 这样的普通输入,表单和结果工作正常,但对于像
that's 这样的特殊字符输入,输出是 that's.
如何获取发送到表单的值?

您必须替换角色实体。我认为 Javascript 中没有执行此操作的本地方法(如果有人请评论或添加答案)。但幸运的是,手动操作非常简单:

// The list of characters to escape
const htmlEscapes = {
  '&': '&',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#x27;',
  '/': '&#x2F;'
};

// Sample string with an apostrophe character entity in it
let str = 'that&#x27;s';

// Loop over the entities to escape and regex them out
Object
  .entries(htmlEscapes)
  .forEach(([plain, hexCode]) => str = str.replace(new RegExp(hexCode, 'g'), plain));

// String is now sanitized
console.log(str);

这只是一种示例方法,重点是您必须处理字符串才能替换它们

您是如何获得数据的?

function Form() {
  const [comm,setComm] = React.useState()

  const submitHandler = e => {
    e.preventDefault()
    const data = new FormData(e.target)
    setComm(data.get('comment'))
  };

  return (
    <form onSubmit={submitHandler}>
      <input
        name="comment"
        type="text"
      />
      <button type="submit">
        submit
      </button>
      <div>Result : {comm}</div>
    </form>
  );
}