简体   繁体   中英

How to pass ref to component in React?

I am using a library called react-swipe (not especially relevant), which exposes next() and prev() methods on the instance, which I am accessing through a ref.

When I have the ReactSwipe component in my main App.js file this works perfectly well, eg:

_handlePrev() {
    this.reactSwipe.prev()
}

_handleNext() {
    this.reactSwipe.next()
}

render() {

    let singlePlanets

    singlePlanets = this.state.planetData.map(data => {
        return (
            <div className="single-planet" key={data.id}>
                <div className="image">
                    <img src={emptyPlanet} alt={data.name} />
                </div>
                <h2>{data.name}</h2>
                <div className="extract" dangerouslySetInnerHTML={{ __html: data.extract }} />
            </div>
        )
    })

    return (
        <div className="app-container">
            <TitleBar />
            <ReactSwipe ref={reactSwipe => this.reactSwipe = reactSwipe} className="content" key={singlePlanets.length}>
                {singlePlanets}
            </ReactSwipe>
            <MenuBar handleNext={this._handleNext.bind(this)} handlePrev={this._handlePrev.bind(this)} />
        </div>
    )
}

But what I'm trying to do is separate out the ReactSwipe and planetData mapping logic into its own component (code below), however when I do this (by trying to pass the ref through as a prop) I always get the error this.reactSwipe.prev() (or .next()) is not a function, no matter what I try. I'm wondering - what is the correct way to go about this?

This what I have in my return in App.js:

<PlanetInfo planetData={this.state.planetData} swipeRef={reactSwipe => this.reactSwipe = reactSwipe} />

and in PlanetInfo component:

return (
        <ReactSwipe ref={this.swipeRef} className="content" key={singlePlanets.length}>
            {singlePlanets}
        </ReactSwipe>
    )

替换ref={this.swipeRef}ref={this.props.swipeRef}PlanetInfo组件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM