javascript - 为什么我的 for 循环在 React 中的 render 方法之前在我的类中不起作用?

标签 javascript reactjs jsx

我在这里找到了几个实际上解决这个问题的答案,这就是为什么我找到了我的一般方法。但正如大多数答案所说,插入代码片段:

var squares =[];

for(let i=1; i<10; i++){

    squares.push(<div className="square" key={i}></div>);       
}

在 render 方法之前的类中。但它不起作用。然后我将相同的代码放在类之外并且它可以工作但是现在我无法访问状态范围(如果我没记错的话)。我也很困惑,为什么我的代码编辑器不允许我将 var 更改为 let(类内)。

有什么想法吗?

谢谢。

最佳答案

most answers say insert the code snippet inside the class before the render method. But it does not work.

这些答案可能意味着:

someMethod() {
  var squares =[];

  for(let i=1; i<10; i++){
     squares.push(<div className="square" key={i}></div>);       
  }
}

render() {
  return (
     // ...
  )
}

鉴于您可能正在这样做:

var squares =[];

for(let i=1; i<10; i++){
   squares.push(<div className="square" key={i}></div>);       
}

render() {
  return (
     // ...
  )
}

Then I put the same code outside off the class and it works but now I have no access to the state scope

没错,本该如此。

我还怀疑你想在屏幕上显示这个,在这种情况下你也应该返回它:

someMethod() {
  var squares =[];

  for(let i=1; i<10; i++){
     squares.push(<div className="square" key={i}></div>);       
  }
  return squares;
}

render() {
  return (
    <div>
     {this.someMethod()}
    </div>
  )
}

关于javascript - 为什么我的 for 循环在 React 中的 render 方法之前在我的类中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47620961/

相关文章:

javascript - 如何过滤包含键和值的数组

javascript - 如果根/父元素向上/向下滚动则显示按钮,如果不是则隐藏该按钮

reactjs - Apollo 客户端 useLazyQuery 未启动

javascript - ReactJS中动态生成的输入文本字段值设置问题

javascript - 如果我希望在加载页面时立即触发它,我应该在此处放置什么 jQuery 方法?

javascript - react JS : Refactoring Redux Selectors

javascript - React + .jsx + Spread 运算符——添加样式?

javascript - 无法在 React.js 上从 svg 加载图像

css - 为什么设置了 dialogClassName 和使用 Styled JSX 的 Bootstrap 模态样式需要全局标记?

javascript - 使用 jQuery 创建嵌套列表