我最近启动了React,现在陷入了矩阵问题。列和行是用户的输入,应显示矩阵作为输出。这是我的代码:
class App extends Component {
constructor(props){
super(props);
this.state = {
array1 : [],
array2 : [],
col1: null,
row1 : null,
}
this.handleCol1Change = this.handleCol1Change.bind(this);
this.handleRow1Change = this.handleRow1Change.bind(this);
}
handleCol1Change(e){
this.setState({
col1 : e.target.value
})
}
handleRow1Change(e){
this.setState({
row1 : e.target.value
})
}
createarray1(){
for(let i=0; i < this.state.row1; i++){
let row = []
this.state.array1.push(row);
for(let j=0; j < this.state.col1; j++){
let col = "1"
this.state.array1.push(col);
}
return this.state.array1
}
}
handleSubmit(){
this.createarray1()
}
render() {
return (
<div>
<h3>Enter Dimensions</h3>
<form>
<h1>Matrix 1</h1>
<input placeholder="Columns" onChange={this.handleCol1Change}/>
<input placeholder="Rows" onChange={this.handleRow1Change}/>
<button type="submit" onSubmit={this.handleSubmit.bind(this)}>Enter Dimensions</button>
</form>
{console.log("array",this.state.array1,"array2",this.state.array2)}
</div>
);
}
}
我相信错误在于我的创建数组逻辑。在console.log
它表明我的数组没有任何存储。关于我在做什么错的任何想法吗?TIA
在createArray()方法中有几个问题,您需要构建该行,然后将其添加到数组中。另外,正如@ageoff所说,您需要致电setState
而不是this.state
直接使用。这是对您的代码进行的更改,以使其与当前的代码保持相似-但它应该可以工作。
createarray1
现在只返回数组,该handleSubmit
函数设置状态。
编辑:我现在已更改,createarray1
以便它是一个纯函数,并且您传入rowCount和colCount。现在,您可以检查是否可以createarray1
独立运行:
createarray1(rowCount, colCount){
let myarr = [];
for(let i=0; i < rowCount; i++){
let row = []
for(let j=0; j < colCount; j++){
let col = "1"
row.push(col);
}
myarr.push(row);
}
return myarr;
}
handleSubmit(){
this.setState({
array1: this.createarray1(this.state.row1, this.state.col1)
});
}
这是一个单独的函数,用于说明它正在创建正确的数组:
let createarray1 = function(rowCount, colCount){
let myarr = [];
for(let i=0; i < rowCount; i++){
let row = []
for(let j=0; j < colCount; j++){
let col = "1"
row.push(col);
}
myarr.push(row);
}
return myarr;
}
console.log(createarray1(2,3));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句