【问题标题】:Loop function inside html in javascript (React) [duplicate]javascript(React)中html中的循环函数[重复]
【发布时间】: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;

这是正确的方法,还是有更好的方法?

【问题讨论】:

标签: javascript html reactjs three.js grommet


【解决方案1】:

您应该使用componentDidMount 挂钩而不是onload

componentDidMount() 在组件安装后立即调用(插入到树中)。需要 DOM 节点的初始化应该放在这里(就像你的情况一样)。

在此处阅读有关componentDidMount 的更多信息 - https://reactjs.org/docs/react-component.html#componentdidmount

【讨论】:

    【解决方案2】:

    在反应中,您可以在“HTML”(这称为 JSX)中编写 Javascript。您不必在函数组件之外编写任何 Javascript 逻辑。

    此外,您不必使用 innerHTML,而是必须用 JSX(在 HTML 内部)编写,并使其在每次循环运行时返回一个组件实例。

    要替换 "onload",您可以使用名为 componentDidMount 的钩子。

    关于如何在 JSX 中(HTML 内)编写循环逻辑的问题,here is a link to a similar question

    【讨论】:

      猜你喜欢
      • 2015-08-14
      • 2017-07-31
      • 1970-01-01
      • 2020-11-18
      • 2012-03-03
      • 2021-11-19
      • 1970-01-01
      • 2015-02-21
      • 1970-01-01
      相关资源
      最近更新 更多