javascript - 如何将子元素附加到 React 元素

标签 javascript reactjs react-native

我想用循环将子元素附加到我的主 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
}

最佳答案

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

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

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

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

如果您不喜欢此方法,您仍然可以使用 forwhile 关键字。
编辑:参见@mangartanswer for 方法使用 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>

关于javascript - 如何将子元素附加到 React 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58200373/

相关文章:

javascript - Yeoman webapp 部署,我的 json 文件不起作用

javascript - 如何知道 service worker 是否在 gatsby-plugin-offline 中更新

reactjs - 在 React Native ios 应用程序中无法识别 fontFamily

javascript - 在 Redux 中使用组件状态是反模式吗?

javascript - 我如何传递带有状态的函数以响应 useContext

react-native run-ios 不运行应用程序,但从 xcode 构建它可以工作

reactjs - 使用 react-native-print 时如何设置 HTML 样式

javascript - 为什么包含 $(从字符串构建)的正则表达式不起作用?

Javascript 过滤列表并从中返回匹配的项目

javascript - 我不想看到网址中的所有内容