【发布时间】:2021-02-28 19:53:09
【问题描述】:
我有一个二维数组作为父组件中的状态,它代表一个网格。外部数组是
容器数组,内部数组包含 GridItem 组件,表示网格上的单元格。 GridItem 组件具有节点类型、节点重量等状态数据。我想遍历二维数组并获取每个 GridItem 的状态值以进行进一步处理。
问题:
我无法通过迭代 GridItems 数组直接从父组件访问/获取状态值。e.g console.log(this.state.gridState[0].props.children[0]) <- returns the GridItem but it's state and other than passed prop values are inaccessible;
我尝试为子组件类编写回调方法,但我认为没有办法从父组件“激活”此回调。尽管我设法编写了一个回调来设置 GridItem 值,只要它们被单击。
我也尝试过使用 refs,但发现对数组中的 1000 多个组件使用 refs 可能并不明智。
我对反应还是很陌生,这就是为什么我认为我的编码方式可能存在根本性的错误。我什至可以将这些组件存储在数组中还是应该以其他方式执行此操作?
Grid.jsx(只有必要的方法)
class Grid extends React.Component
{
constructor(props){
super(props);
this.state = {
gridRowCount: 35,
gridColCount: 72,
gridState: [],
};
this.gridWasClicked = this.gridWasClicked.bind(this);
}
initGrid(){
let counter = 0;
for(let i = 1; i < this.state.gridRowCount+1; i++)
{
let tmpRow = [];
for(let j = 1; j < this.state.gridColCount+1; j++)
{
tmpRow.push(<GridItem key={counter} gridIndex={[j, i]} gridWasClicked={this.gridWasClicked}/>);
counter++;
}
this.pushElemToGrid(<div key={counter} className="grid-row">{tmpRow}</div>);
}
this.iterateGrid();
}
GridItem.jsx(仅必要的方法)
class GridItem extends React.Component
{
constructor(props)
{
super(props);
this.state = {
isVisited: false,
nodeWeigth: 0,
gridIndex: [0,0],
nodeType: 0,
};
}
componentDidMount()
{
this.setState({gridIndex: [this.props.gridIndex[0], this.props.gridIndex[1]]});
}
render(){
return(
<div className="grid-item" onClick={this.cellWasClicked}>
{this.state.nodeType}
</div>
);
}
【问题讨论】:
-
为什么需要
GreedItem组件的状态?