【问题标题】:How to retrieve real value from html symbols in jsx?如何从 jsx 中的 html 符号中检索实际值?
【发布时间】:2021-03-02 05:06:03
【问题描述】:

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

【问题讨论】:

    标签: html reactjs jsx special-characters


    【解决方案1】:

    您必须替换角色实体。我认为在 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);
    

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

    【讨论】:

    • 本地的做法会很好。但这工作得很好。感谢您的解决方案。
    【解决方案2】:

    您是如何获得数据的?

    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>
      );
    }
    

    【讨论】:

    • 我正在使用类组件。但这很像您的代码。功能组件自己解决问题吗?
    • 功能组件的渲染方式相同。不同之处在于功能的范围更大。但是在这个例子中,一个类组件应该有相同的结果:-/
    • 是的。结果应该是一样的。无论如何感谢您的建议。我也会尝试使用功能组件,看看它是否有效。
    猜你喜欢
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    相关资源
    最近更新 更多