javascript - 如何将 ref 传递给 React 中的组件?

标签 javascript reactjs

我正在使用一个名为react-swipe(不是特别相关)的库,它在实例上公开 next() 和 prev() 方法,我通过引用访问该方法。

当我的主 App.js 文件中有 ReactSwipe 组件时,它工作得很好,例如:

_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>
    )
}

但是我想做的是将 ReactSwipe 和 PlanetData 映射逻辑分离到它自己的组件中(下面的代码),但是当我这样做时(通过尝试将 ref 作为 prop 传递)我总是得到错误 this.reactSwipe.prev() (或 .next()) 不是一个函数,无论我尝试什么。我想知道 - 正确的方法是什么?

这是我在 App.js 中返回的内容:

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

在 PlanetInfo 组件中:

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

最佳答案

PlanetInfo 组件中的 ref={this.swipeRef} 替换为 ref={this.props.swipeRef}

关于javascript - 如何将 ref 传递给 React 中的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50336502/

相关文章:

javascript - 部署到 github 页面后,Axios 从文件中获取数据不起作用

javascript - jQuery FullCalendar 回归 1970 年

javascript - 使用jquery自动刷新图像

javascript - 为什么在 API 调用和 setState 之后,同一对象的某些元素可以访问,而其他元素则不可访问?

javascript - ComponentDidMount 等不会按顺序触发函数

javascript - ES6 映射在对象数组上抛出错误

css - 在某些情况下,div 的宽度会增加,即使我有溢出 :auto

c# - 有没有办法自动将 View 模型对象映射到 javascript 对象?

javascript - WebGL "ERROR: unsupported shader version"

javascript - 是否可以将函数传递给 casper.evaluate()?