如何在appendchild方法javascript或reactjs中使用文件夹路径中的svg? [英] How to use svg from the folder path in appendchild method javascript or reactjs?
问题描述
我是 reactjs 的新手,我坚持将 svg 元素附加到 div 元素.
i am new to reactjs and i stuck with appending svg element to the div element.
我想实现什么?我有一个动态创建的 div 元素,如下所示.
What is that i want to implement? I have a div element created dynamically like below.
constructor(props) {
super(props);
this.element = document.createElement('div');
}
我有一个 svg 导入到组件中,如下所示从 '../svg/name.svg' 导入 SvgName;
I have a svg imported to the component like below import SvgName from '../svg/name.svg';
并希望将此 SvgName 附加到在上述构造函数中动态创建的 div 元素.
and want to append this SvgName to the div element created dynamically in the above constructor.
我尝试过的……在下面,
What i have tried....is below,
constructor(props) {
super(props);
this.element = document.createElement('div');
const svg = document.createElement('svg');
this.element.appendChild(svg);
}
上面将附加一个 svg 元素,但它没有添加我想要的 svg(导入的那个).
The above will append a svg element however it doesnt add the svg that i want (the one imported).
我怎样才能实现它.谢谢.
How can i achieve it. Thanks.
推荐答案
您示例中的 svg
元素是一个 React 组件,因此可以使用 ReactDOM.render 在 DOM 元素内呈现它
,就像这样:
The svg
element in your example is a react component, so it can be rendered inside DOM elements with ReactDOM.render
, like that:
componentDidMount() {
ReactDOM.render(<SvgComponent />, this.element);
}
ReactDOM.render
调用不一定必须在 componentDidMount
处理程序中,您可以在您喜欢的组件生命周期的任何部分使用它,只要 this.element
是一个初始化的 DOM 元素.
The ReactDOM.render
call does not necessarily have to be in the componentDidMount
handler, you can use it in whatever part of the lifecycle of the component you feel like, as long as this.element
is an initialized DOM element.
这篇关于如何在appendchild方法javascript或reactjs中使用文件夹路径中的svg?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!