我有一个使用document.createElement()的javascript库,它创建了一个HTMLElement,我想创建一个具有相同功能的react库。我的想法是用React.createElement()取代document.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调用后更改道具和显示子对象的具体问题
发布于 2021-07-29 00:11:15
创建一个props对象,并将其作为createElement函数的第二个参数传递。遵循这一点-
const props = {
className: 'someClassName',
style: {
display: 'block',
width: '100%'
}
}
React.createElement('input', props);发布于 2021-07-29 00:08:59
阅读React.createElement的文档。您可以在函数中传递props (和子对象)。
https://stackoverflow.com/questions/68563818
复制相似问题