【问题标题】:React-Native ref of child component for drop down用于下拉的子组件的 React-Native ref
【发布时间】:2015-12-03 22:50:46
【问题描述】:

我正在使用 react-native-dropdown,但无法在 listview 组件中获取组件的引用。当我将下拉列表添加到列表视图行时,我需要将 ref 分配给其中的选择组件,但引用返回未定义,因为只有顶级视图组件可以与 ref 一起使用。有没有可能的解决方案。请帮忙。代码如下:

在主渲染中:

<ListView ref='listView'
   style = {{ backgroundColor: '#EAEAEC'}}
   dataSource={this.state.dataSource}
   automaticallyAdjustContentInsets={false}
   renderRow={this.renderRow} />

在渲染行中:

<View style={{flex:2.5, justifyContent:'center', alignItems:'center'}}>
    <Select
       width={250}
       ref="SELECT1"
       optionListRef={() => {this._getOptionList()}}
       defaultValue="Select a Province in Canada ..."
       onSelect={ (index) => {console.log(index, 'is selected.');} }>
       <Option>Alberta</Option>
       <Option>British Columbia</Option>
       <Option>Manitoba</Option>
       <Option>Yukon</Option>
    </Select>
  <OptionList ref="OPTIONLIST"/>
</View>

现在,我需要将带有 ref OPTIONLIST 的 OptionList 标记分配给 select 的 optionListRef 属性,但由于这不是顶级视图,所以 this.refs["OPTIONLIST"] 返回 undefined

【问题讨论】:

  • 我怀疑您不需要 ref,相反,您应该在输出它们的循环中每个子项的闭包中定义回调函数。如果您包含一些代码,我可以更具体,但请参阅此示例:facebook.github.io/react/tips/…
  • @AdamTerlson 我已添加代码,请检查。

标签: react-native


【解决方案1】:

renderRow 被赋予 rowData 作为参数 (https://facebook.github.io/react-native/docs/listview.html)。

在该函数中,重新定义所有内联箭头函数以将此 rowData 传递给公共处理程序。

例子:

renderRow(rowData) {
    ...
    optionListRef={() => this._getOptionList(rowData)}
},

_getOptionList(rowData) {
   // Use rowData
}

附带说明一下,箭头函数中不需要大括号,除非它是多行的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多