javascript - Display Multi Dimensional Arrays/Matrix using react
问题描述
I started React recently and I am stuck on a matrix issue. Columns and Rows are taken as input from the user and should display a matrix as output. Here is my code:
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>
);
}
}
I believe the fault is in my create array logic. On console.log
it shows that my array is not storing anything. Any ideas on what I'm doing wrong?
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));
推荐阅读
- swift - 使用 XMPPFramework CoreData 存储文件
- gwt - GWT Material DatePicker 在选项卡更改时自动打开
- android - 使用 SQLiteDataBase 获取常量值
- ionic-framework - Ionic 2 如何动态搜索 Estimote Beacon
- python - itertools.combinations 的保证是什么?
- python - 如何在python中获取内存中复杂对象的二进制表示(打开“rb”)?
- android - Android如何设置ImageButton可访问性焦点
- r - 无法在 Rshiny 中显示绘图
- javascript - Laravel:从控制器获取错误响应,但在控制台上键入错误并且响应消息未显示在视图页面上
- javascript - 使用 Electron 时,设计 HTML/CSS 布局的最佳方式是什么?