如何解决在反应中渲染 html div
'一旦我在 plotly 中生成了一个简单的图形并将其保存为 html div 元素,我该如何在 react 应用程序中呈现它?已经有 here 和 here 的危险设置内部HTML 的问题和解决方案。事实是反应应用程序不会渲染它,即使使用库 dompurify 也不会引发任何错误,所以我想知道我是否遗漏了什么,或者使用它是否有任何关于情节的问题......
使用 Networkx 创建 Python 图
import matplotlib.pyplot as plt
import random
import networkx as nx
import plotly.graph_objects as go
import plotly.io as pio
import plotly
# a simple graph by networkx
G = nx.path_graph(8)
# Graph setup; positions,text,etc
pos = nx.spring_layout(G)
for i in range(len(G.nodes)):
G.nodes[i]["pos"] = pos[i]
edges = ['E_' + str(i) for i in range(len(G.nodes))]
edge_x = []
edge_y = []
ytext=[]
xtext=[]
for edge in G.edges():
x0,y0 = pos[edge[0]]
x1,y1 = pos[edge[1]]
xtext.append((x0+x1)/2)
ytext.append((y0+y1)/2)
edge_x.append(x0)
edge_x.append(x1)
edge_x.append(None)
edge_y.append(y0)
edge_y.append(y1)
edge_y.append(None)
# build plotly graph object instance ans setups
edge_trace = go.Scatter(
x=edge_x,y=edge_y,line=dict(width=0.5,color='#888'),hoverinfo='none',mode='lines')
node_x = []
node_y = []
for node in G.nodes():
x,y = pos[node]
node_x.append(x)
node_y.append(y)
edge_texts=[f'id: {n}' for n in edges]
edge_trace = go.Scatter(
x=edge_x,hoverinfo='text',text= edge_texts,textposition='middle center',textfont=dict(
size=5
),mode='lines')
eweights_trace = go.Scatter(x=xtext,y=ytext,mode='text',hovertext=edges,marker_size=0.5,textposition='top center',)
colormap = ["#FF0000" for i in range(len(G.nodes))]
symbols = [1 for i in range(len(G.nodes))]
names = ["N_"+str(i) for i in G.nodes()]
descriptions = ["foo","bar","buz","qux","quux","quuz","foo","quuz"]
types = ["corge","grault","garply","waldo","fred","plugh","xyzzy","thud","corge",]
node_texts=[f'id: {i}<br>Description: {j}<br>Type: {k}<br>Name: {l}<br>Coordination: {m}' for
i,j,k,l,m in zip(G.nodes(),descriptions,types,names,pos.values())]
node_trace = go.Scatter(
x=node_x,y=node_y,mode='markers',marker_symbol=symbols,hoverinfo='text+x+y',text= node_texts,marker=dict(
showscale=False,colorscale='Hot',reversescale=True,color=[],size=15,colorbar=dict(
thickness=0,xanchor='left',titleside='right'
),line_width=2))
node_adjacencies = []
node_text = []
for node,adjacencies in enumerate(G.adjacency()):
node_adjacencies.append(len(adjacencies[1]))
node_text.append(descriptions[node])
node_trace.marker.color = colormap
layout=go.Layout(autosize=False,width=500,height=500,title='<br>The graph of example',titlefont_size=24,showlegend=False,hovermode='closest',margin=dict(l=5,r=5,b=10,t=10,pad = 2),annotations=[ dict(
showarrow=False,xref="paper",yref="paper",x=0.005,y=-0.002 ) ],xaxis=dict(showgrid=False,zeroline=False,showticklabels=False),yaxis=dict(showgrid=False,showticklabels=False))
fig = go.figure(data=[edge_trace,node_trace,eweights_trace],layout=layout);
# if verification needed
fig.show()
# save it as a div
divastext = plotly.offline.plot(fig,include_plotlyjs=True,output_type='div')
file = open("divastext.txt","w")
file.write(divastext)
file.close()
JavaScript 和 React 部分
import './App.css';
import createDOmpurify from 'dompurify'
import { JSDOM } from 'jsdom'
const window = (new JSDOM('')).window
const DOmpurify = createDOmpurify(window)
function App() {
getGraph();
async function getGraph() {
const response = await fetch("divastext.txt");
const rawHTML = await response.text();
}
return (
<div className="DivAsText">
{ <div dangerouslySetInnerHTML={{ __html: DOmpurify.sanitize(rawHTML) }} /> }
</div>
);
}
export default App;
有没有更干净的方法来渲染这个情节生成的 div 反应? 非常感谢。
解决方法
我觉得应该是
<div dangerouslySetInnerHTML={{ _html: rawHTML}}></div>
因为你已经将你的 div 包裹在花括号中,如下所示
{ <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(rawHTML_) }} /> }
,
这有点令人困惑,但我认为您可以将 divastext 保存为大写并像处理任何其他组件一样呈现它:<DivAsText />
。你可以试试吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。