我正在使用一个名为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/