我有一个 javascript 库,它使用 document.createElement()
创建一个 HTMLElement
我想创建一个具有相同功能的反应库。
我的想法是用 document.createElement()
替换 React.createElement()
。
所以,原始代码类似于
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);
将成为
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
这里的问题是 props 是 react 中的只读属性, appendChild 也不能那样工作。因此在 React.createElement("input")
之后更改它是不可能的。我可以在基于原始代码的每次 createElement 调用之前创建 props 对象,但它显着降低了现有代码库的可重用性。有没有办法在 react 中绕过这个问题?
编辑:我知道我可以在调用 React.createElement 期间传递子项和道具,但是,它降低了我复制粘贴和重用现有代码库的能力。这个问题是关于在 React.createElement 调用之后改变道具和附加孩子的问题
答案 0 :(得分:1)
创建一个 props 对象并将其作为 createElement 函数的第二个参数传递。按照这个-
const props = {
className: 'someClassName',
style: {
display: 'block',
width: '100%'
}
}
React.createElement('input', props);
答案 1 :(得分:0)
阅读 React.createElement
的文档。您可以在函数中传递道具(和子项)。