React 元素中 $$typeof 的作用-xss防范

3 阅读1分钟

react Fiber 节点中 有遇到 用React 元素中 $$typeof

原因

  1. 标识 是react 元素
  2. 防止XSS攻击

XSS


render() {
  return (
    <div>
      {{
        $$typeof: Symbol.for('react.element'),
        props: {
          dangerouslySetInnerHTML: {
            __html: '<img src="x" onerror="alert(1)">'
          },
        },
        ref: null,
        type: "div",
      }}
    </div>
  );
}


这段代码,其实是可以直接允许的,会存在xss工具

因此后续

{
  $$typeof: Symbol.for('react.element'),
  props: {
    id: 'container'
  },
  ref: null,
  type: "div",
}

使用 Symbol 类型是因为 JSON 中无法传递 Symbol ,至于名称,可能更多的是为了区别其他属性