【问题标题】:Given an array of child components, how to access their state data from parent component?给定一个子组件数组,如何从父组件访问它们的状态数据?
【发布时间】: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组件的状态?

标签: arrays reactjs jsx


【解决方案1】:

您需要以不同的方式思考这个问题 - GridItem 应该是一个“愚蠢”的组件,由 Grid“控制”; Grid 通过传递 props 来控制 GridItemGridItem“反应”它传递的道具。因此,您实际上不需要知道GridItem 的状态,具体来说,它在任何时候传递的道具是什么,Grid 总是知道这一点。所以只需通过 props 从Grid 控制GridItem。这有帮助吗?

【讨论】:

  • 是的,我明白你的意思。我开始意识到这就是 React 组件的使用方式。感谢您的确认和有用的回答!
  • 欢迎您,很高兴我能帮上忙!这只是因为你是 React 的新手——一旦点击就可以了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-14
  • 2023-02-25
  • 1970-01-01
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多