ReactJS - 在兄弟姐妹之间传递引用

时间:2017-05-03 08:12:19

标签: javascript reactjs recursion tree siblings

我目前在构建我的ReactJS应用时遇到问题。我有一个采用这种形式的数组:

[{
   _id: 123456,
   ...
   children: [
      {
         _id: 568,
         ...
         children: [...] // and so on, recursively
      },
      ....
   ]
}]

这种架构需要呈现为一些“进化树”,如:

| item | => | item's first child  | => | first child's first child | ..
|      | => | item's second child |

每个“item”或“child”是一个组件(名为EvolutionStep),每个“=>”箭头是另一个组件(称为EvolutionArrow)。所以我们有三个组成部分:

Evolution Chain => parent component, that renders
Evolution Step => containing the evolution props (name, etc)
Evolution Arrow => linking one step to one of it's children. 

进化箭头需要指向渲染下一个进化步骤的方向(在该示例中,项目和项目的第一个孩子之间的第一个箭头将指向直线,但是如果项目的第一个孩子的位置是{{1}箭头应指向上方。

为了实现这一点,每个Evolution Step在渲染时都会调用Evolution Chain中的函数来添加对本地状态的引用。每个Evolution Arrow在渲染时都会传递对它应该指向的Evolution Step的引用。问题是Evolution Arrow的{top: -20px}道具始终未定义......

我不知道我是否正确解释了自己,所以这是我的代码。请注意,如果在Evolution箭头类中放置了console.log(this.props.references),它始终是未定义的。

提前感谢您的帮助!

reference

2 个答案:

答案 0 :(得分:0)

修正了它!我所要做的只是将undefined包裹在stepDidMount的引号中,否则条件总是错误的......

答案 1 :(得分:0)

参考 componentDidMount()可以解决问题。

以下代码可帮助我设置两个兄弟之间的通信。设置在render()和componentDidMount()调用期间在其父级中完成。 它基于https://reactjs.org/docs/refs-and-the-dom.html

class App extends React.Component<IAppProps, IAppState> {
    private _navigationPanel: NavigationPanel;
    private _mapPanel: MapPanel;

    constructor() {
        super();
        this.state = {};
    }

    // `componentDidMount()` is called by ReactJS after `render()`
    componentDidMount() {
        // Pass _mapPanel to _navigationPanel
        // It will allow _navigationPanel to call _mapPanel directly
        this._navigationPanel.setMapPanel(this._mapPanel);
    }

    render() {
        return (
            <div id="appDiv" style={divStyle}>
                // `ref=` helps to get reference to a child during rendering
                <NavigationPanel ref={(child) => { this._navigationPanel = child; }} />
                <MapPanel ref={(child) => { this._mapPanel = child; }} />
            </div>
        );
    }
}
相关问题