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

时间:2018-05-14 18:07:13

标签: javascript reactjs

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

当我在我的主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作为道具传递)我总是得到错误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>
    )

1 个答案:

答案 0 :(得分:1)

Private Sub InputData () Dim Sheet2Exists As Boolean Dim i As Long DayNumber = 1 'First day in month MonthDayMaximum = InputBox("Input Days in Month","Input Prompt",0) + 1 Sheet2Exists = False Application.ScreenUpdating = False Do While DayNumber <> MonthDayMaximum For i = 1 to Worksheets.Count If Worksheets(i).Name = "Sheet1 (2)" Then 'Testing for other sheet added previously Sheet2Exists = True End If Next i Application.ScreenUpdating = True Sheets("Sheet1").Activate UserForm1.Show vbModeless Do While UserForm1.Visible 'Desktop macro inputs data, then closes Userform DoEvents Loop MsgBox "Sheet1 Data Inputted", vbOKOnly, "Sheet1" 'Tells desktop macro to move on If Sheet2Exists = True Then Sheets("Sheet1 (2)").Activate UserForm2.Show vbModeless 'Macro recognizes different userforms Do While UserForm2.Visible DoEvents Loop MsgBox "Sheet1 (2) Data Inputted", vbOKOnly, "Sheet1 (2)" End If Application.ScreenUpdating = False Call Classify 'Follows other procedures for inputted data DayNumber = DayNumber + 1 Loop End Sub 替换为ref={this.swipeRef}组件中的ref={this.props.swipeRef}