【问题标题】:How to append child to React element?如何将子元素附加到 React 元素?
【发布时间】:2019-10-02 11:15:06
【问题描述】:

我想用循环将孩子附加到我的主 div

let mainContainer = React.createElement("div", { className: "contexCon" });

喜欢这个

for(let i = 0; i < 3; i++){
    mainContainer.appendChild(child[i]) // this will not work just as example
}

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    TL;DR: React 接受数组 React Node 作为子节点。

    componentDidMountcomponentWillUnmount 中执行您的 fetch API 操作。 “为什么?”如果你问。因为,如果你使用内置的 React 生命周期处理异步任务会更安全。因此,如果组件在提取完成后消失或类似情况,您的组件中不会有未处理的提取。

    但在这种情况下,我不会使用状态和/或任何生命周期,因为我的数据是虚拟的和静态的。

    您说的是循环,但我很确定这意味着循环将您的数据放入 html 元素。所以,如果你使用Array.prototype.map()会更简单。基本上,它将循环数组和回调函数,并将其返回值作为一个新数组。

    如果您不喜欢这种方法,您仍然可以使用 forwhile 关键字。
    编辑:请参阅@mangartanswer 了解使用for 关键字的方法。

    // example
    const array = [2, 3, 4];
    const arrayMap = array.map((val) => val * 2) // [4, 6, 8]
    

    class App extends React.Component {
      myData = [
        {key: 1, name: "Hello"},
        {key: 2, name: "World"},
        {key: 3, name: "etc"}
      ];
      render() {
        // the loop. it'll return array of react node.
        const children = this.myData.map((val) => (
          <button id={val.key}>{val.name}</button>
        ));
        // the div with children inside
        return (
          <div className="contexCon">
            {children}
          </div>
        );
      }
    }
    
    // render your app
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App/>, rootElement);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="root"/>

    基于函数的元素,没有 JSX。

    function App() {
      // the data
      const myData = [
            {key: 1, name: "Hello"},
            {key: 2, name: "World"},
            {key: 3, name: "etc"}
          ];
      // the loop
      const children = myData.map((val) => (
          React.createElement("button", {id: val["key"]}, val["name"])
      ));
      // the div with children inside
      return (
        React.createElement("div", {className: "contexCon"},
          children
        )
      );
    }
    
    // render
    ReactDOM.render(React.createElement(App, {}), document.getElementById("root"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="root">
    <style>.contexCon {background-color: yellow; margin: 8px 0;}</style>

    【讨论】:

    • 嗨,Nouvist,您能否在回答中用单词和句子解释您提出的解决方案是什么?
    【解决方案2】:

    React.createElement 有这样的签名:

    React.createElement(
      type,
      [props],
      [...children]
    )
    

    所以第三个参数应该是你的孩子的数组。在您的示例中,您似乎可以这样做:

    let mainContainer = React.createElement("div", { className: "contexCon" }, child);
    

    const headline = React.createElement('h1', {}, 'Hello, World!');
    const body = React.createElement('p', {}, 'Lorem ipsum dolor sit amet');
    const X = React.createElement('div', {}, [headline, body]);
    
    ReactDOM.render(X, document.getElementById('app'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="app"></div>

    【讨论】:

    • 但是如果我想用循环 const X = React.createElement('div', {}, [headline, body]); 附加子元素怎么办?
    【解决方案3】:

    我刚刚遇到了将子元素附加到父元素的同样问题。我如何解决这个问题是在创建父元素之前创建子元素并将它们添加到数组中。然后,当您创建父元素时,您只需将之前创建的子元素数组传递给它。因此,在您的情况下,5 个子 div 元素的代码如下所示:

    var elements = [];
    for(let i = 0;i < 5;i++){
        elements.push(React.createElement("div",null));
    }
    let mainContainer = React.createElement("div", { className: "contexCon" },elements);
    

    【讨论】:

      【解决方案4】:

      另外,如果你想使用 DIV 元素来像控制台一样显示消息,最好的方法是使用这样的纯 JavaScript:

      consoleMessage = (text_msg) =>
      {        
          let parr = document.createElement('p');
              parr.setAttribute('class','message');
              parr.innerHTML = text_msg;
          
          let consoleLine = document.getElementById("Console");        
          
              consoleLine.appendChild(parr);   
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-26
        • 2021-10-26
        • 2019-10-16
        • 2023-01-16
        • 1970-01-01
        • 2021-01-20
        • 2021-04-18
        • 2020-04-17
        • 2015-06-22
        相关资源
        最近更新 更多