在 React by for 循环中渲染组件



我想制作 vor 示例 x=3、x=3,还有 9 个按钮,我不知道为什么当我把它放在我的 for 循环中时它不起作用。 使用带有"render(( 按钮"的渲染按钮方法。当我做一个 conole 时.log它渲染了 9 次,我想它有道具或状态的东西,但我不知道如何修复它

import React,{ Component } from "react";
import Buttons from "./Buttons";
class Square extends Component{
state={
x:"",
y:"",
maze:"",
}



addButtons(){
var s=this.state.x*this.state.y
for(var i=0;i<s;i++){
console.log("test")

}

}

render(){
const x= this.state.x
const y= this.state.y
const all= x*y
return(
//speichern von x und y in state
<div id="total">

<div id="xvalue">
x
<input onChange={event=>this.setState({x: event.target.value})}></input>
</div>
<div id="yvalue">
y
<input onChange={event=>this.setState({y: event.target.value})}></input>
</div>
<div id="button press">

<button onClick={this.addButtons()}> create button </button>

</div>
</div>
)
}
}
export default Square; 

您可能正在寻找这样的东西。 基本上有一个状态来跟踪是否渲染按钮。 打开该标志后,您可以在渲染中渲染 x*y 按钮数

import React, { Component } from "react";
import Buttons from "./Buttons";
class Square extends Component {
state = {
x: "",
y: "",
maze: "",
renderButtons: false
};
addButtons() {
this.setState({ renderButtons: true });
}
render() {
const x = this.state.x;
const y = this.state.y;
const all = x * y;
return (
//speichern von x und y in state
<div id="total">
<div id="xvalue">
x
<input
onChange={event => this.setState({ x: event.target.value })}
></input>
</div>
<div id="yvalue">
y
<input
onChange={event => this.setState({ y: event.target.value })}
></input>
</div>
<div id="button press">
<button onClick={this.addButtons()}> create button </button>
// move this line to where you want these buttons to appear
{this.state.renderButtons && Array(this.state.x * this.state.y)
.fill(0)
.map(b => (
<button></button>
))}
</div>
</div>
);
}
}
export default Square;

最新更新