React - walkthrough ref to sibling

I need to have 2 sibling components, and 1 of them should have a link to another - is this possible?

I tried this:

<button ref="btn">ok</button>
<PopupComponent triggerButton={this.refs.btn} />

And even that

<button ref="btn">ok</button>
<PopupComponent getTriggerButton={() => this.refs.btn} />

But I get undefinedin both situations. Any ideas?

Note: the parent component will not work for me, because I need to have several sets of them, for example

<button />
<PopupComponent />
<button />
<PopupComponent />
<button />
<PopupComponent />

I do not like:

<div>
  <button />
  <PopupComponent />
</div>
<div>
  <button />
  <PopupComponent />
</div>
<div>
  <button />
  <PopupComponent />
</div>
+4
source share
4 answers

Think this question is best answered by docs :

React, , , refs " " " . , , . , " . refs " " - .

, , , - , .

+6

, . , , - React.

, , , , , ( ), .

, :

class A extends React.Component {
    onClick(key) {
        alert(this.refs[key].refs.main.innerText);
    }

    render() {
        var children = [];
        for (var i = 0; i < 5; i++)
            children.push.apply(children, this.renderPair(i));

        return (
            <div>
                {children}
            </div>
        );
    }

    renderPair(key) {
        return [
            <B ref={'B' + key} key={'B' + key} onClick={this.onClick.bind(this, 'C' + key)}/>,
            <C ref={'C' + key} key={'C' + key} onClick={this.onClick.bind(this, 'B' + key)}/>
        ];
    }
}

class B extends React.Component {
    render() {
        return <p ref="main" onClick={this.props.onClick}>B</p>;
    }
}

class C extends React.Component {
    render() {
        return <p ref="main" onClick={this.props.onClick}>C</p>;
    }
}


React.render(<A/>, document.getElementById('container'));

, , . , .

+2

special-props

JSX , (ref key), React, .

, this.props.key (, ) . , (:). , .

0

. render() componentDidMount(). , .

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>
        );
    }
}
0

All Articles