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