React中使用原生html代码

479 阅读1分钟

今天又遇到一个从没遇过的需求,接口返回html代码的字符串形式,要求把html代码的内容展示在页面上,如

<div style='height:20px;'></div>

jsx是可以写html代码的,但是这个style的格式不符合jsx语法,只好借助原生js来实现

const APP = ()=>{
  const ref = useRef(null);
  useEffect(() => {
    let html = '<div style='height:20px;'></div>'
    let div = document.createElement('div');
    div.innerHTML = html;
    ref.current.appendChild(div);
  }
  return (
    <div ref={ref}></div>
  )
}

不知道有没有其他办法。