[英]Replacing document.createElement() with React.createElement()
I have a javascript library which uses document.createElement()
which creates an HTMLElement
I want to create a react library with the same functionality.我有一个 javascript 库,它使用
document.createElement()
创建一个HTMLElement
我想创建一个具有相同功能的反应库。 My idea was to replace the document.createElement()
with React.createElement()
.我的想法是用
React.createElement()
替换document.createElement()
React.createElement()
。
So , the original code which was something like所以,原始代码类似于
this.myElement = document.createElement("input");
/* some stuff happens here due only after which the followig code is run */
this.myElement.className = "someClassName";
this.myElement.style.display = "block";
this.myElement.appendChild(someElement);
will become会变成
this.myElement = React.createElement("input");
this.myElement.props.className = "someClassName";
this.myElement.props.style.display = "block"; // Props is read only at this point
this.myElement.appendChild(someReactElement); // This doesn't work either
The problem here is that props is a read only property in react , also appendChild doesn't work that way in. So changing it after React.createElement("input")
is not possible.这里的问题是 props 是 react 中的只读属性, appendChild 也不能那样工作。 所以在
React.createElement("input")
之后更改它是不可能的。 I can create the props object before each createElement call based on the original code but it significantly reduces reusability of the existing code base.我可以在基于原始代码的每次 createElement 调用之前创建 props 对象,但它显着降低了现有代码库的可重用性。 Is there a way around that can be used to bypass this issue in react ?
有没有办法可以用来绕过反应中的这个问题?
Edit : I know I can pass children and props during the time I call React.createElement however , it reduces my ability to copy paste and reuse the existing code base .编辑:我知道我可以在调用 React.createElement 期间传递子项和道具,但是,它降低了我复制粘贴和重用现有代码库的能力。 The question is specific about changing props and appeding child after the React.createElement call
这个问题是关于在 React.createElement 调用之后更改道具和附加孩子的
Create a props object and pass that as the 2nd argument of the createElement function.创建一个 props 对象并将其作为 createElement 函数的第二个参数传递。 Follow this-
按照这个——
const props = {
className: 'someClassName',
style: {
display: 'block',
width: '100%'
}
}
React.createElement('input', props);
Read the documentation for React.createElement
.阅读
React.createElement
的文档。 You can pass the props (and children) in the function.您可以在函数中传递道具(和孩子)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.