简体   繁体   English

如何危险地使用SetInnerHTML

[英]How to use dangerouslySetInnerHTML

I have html script data.我有 html 脚本数据。

I want to put it in div.我想把它放在div中。 but when I do that It just shows "}" this and that's it.但是当我这样做时,它只显示“}”,仅此而已。

I wonder what I did wrong.我想知道我做错了什么。

When I log newDataHTML, I can get html string.当我登录 newDataHTML 时,我可以获得 html 字符串。

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function App() {

  const getData = () => {
    axios
      .get('/api/data')
      .then( (data) => {
        // get new Data
        const newDataHTML = data.data[0].rule;

        return {__html: newDataHTML};
      })
      .catch( err => console.log(err));
  }

  return (
    <div className="App">
      <Tabs defaultTab="data" onChange={(tabId) => { console.log(tabId) }}>
        <TabList>
          <Tab tabFor="data">New Data</Tab>
        </TabList>
        <TabPanel tabId="data">
          <div dangerouslySetInnerHTML={getData()}></div>;
        </TabPanel>
      </Tabs>
    </div>
  );
}

export default App;

It is not working because you can't return outside.then method and also you will encounter rerender loop... You can put the method in useEffect hook so it runs once and also put the return data in useState...它不起作用,因为您无法返回 outside.then 方法,而且您还会遇到重新渲染循环...您可以将该方法放在 useEffect 挂钩中,使其运行一次,并将返回数据放入 useState...

const [data, setData] = useState();
useEffect(() => {
   const getData = () => {
      axios.get('/api/data').then((res) => {
        const newDataHTML = res.data[0].rule;
        setData({__html: newDataHTML})
      }).catch( err => console.log(err));
   }
   getData();
}, [])

you can now use the data variable in your jsx instead of calling the function in your jsx.您现在可以在 jsx 中使用数据变量,而不是在 jsx 中调用 function。

It will also be nice to use packages like DomPurify to avoid xss attacks.使用 DomPurify 之类的包来避免 xss 攻击也会很好。

https://www.npmjs.com/package/dompurify https://www.npmjs.com/package/dompurify

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM