【发布时间】:2021-12-18 20:14:56
【问题描述】:
我想在 Html 中循环使用具有不同输入的函数 SliderComponent 以创建多个组件。 我在网上找到了这个解决方案,我们使用“id”和“getElementById”构建字符串并以 Html 形式返回,但我无法让它工作。
export function GrommetButtonEx() {
return (
<div>
<Grommet theme={grommetTheme}>
<Sidebar
border={{ color: "grey", size: "medium" }}
width="340px"
background={{ color: "black", opacity: "strong" }}
style={{ borderRadius: "15px" }}
>
<Accordion style={{ color: "grey" }}>
<AccordionPanel
style={{ height: "30px" }}
label={
<Text color="white" weight="bold" size="small">
Joint Position
</Text>
}
>
<div id="output_div"></div>
{/* This works
<SliderComponent
sliderName={"slider 5"}
min={0}
max={17}
step={0.1}
/>
*/}
</AccordionPanel>
</Accordion>
</Sidebar>
</Grommet>
</div>
);
}
window.onload = function () {
var outputHTML = "";
for (var k = 0; k < 5; k++) {
outputHTML +=
'<SliderComponent sliderName={"slider ' +
k +
'"} min={0} max={17} step={0.1}';
}
document.getElementById("output_div").innerHTML = outputHTML;
};
我收到以下错误:
TypeError: Cannot set properties of null (setting 'innerHTML')
在:
document.getElementById("output_div").innerHTML = outputHTML;
这是正确的方法,还是有更好的方法?
【问题讨论】:
-
你肯定错过了这里的概念。你在这里做什么没有意义。加载窗口时运行时反应中没有
window.onload。<SliderComponent是组件而不是元素 -
这个问题展示了如何在 React 中执行循环:Loop inside React JSX 此外,React Docs show how to render multiple objects inside a loop。
标签: javascript html reactjs three.js grommet