似乎很难直接访问视图中的引用。
现在,我有了一个带有单元格的列表视图。在renderRow函数中,我有类似以下内容:
renderRow
renderRowView: function(rowData){ return <View > <TextInput ref="text" /> </View> },
在这种情况下,如果我想使用ref访问此TextInput,它将为undefined。
undefined
我在Github上看到一个线程(https://github.com/facebook/react- native/issues/897)提到了解决此问题的方法,但我仍然不知道如何使用它:
render: function() { return ( <ListView dataSource={this.state.dataSource} renderRow={(rowData, sec, i) => <Text ref={(row) => this.rows[sec][i] = row}>{rowData}</Text> } /> ); },
请帮助我了解此ref函数的工作方式以及使用方法(即以编程方式集中TextInput于该行中的内容)。谢谢!
TextInput
refReact Component上的属性可以是a string或callback函数,它将与组件的第一个参数一起调用。
ref
string
callback
因此,将函数传递给ref属性将在安装组件时执行它,并且组件本身在第一个参数中。
您粘贴的github代码正在执行的操作是在通过refcallback属性安装组件时将组件添加到二维数组中。该row说法在本质上是<TextInput/>本身。
row
<TextInput/>
您想实现什么?可能有一个更简单,更干净的解决方案。
编辑: 关于您要实现的目标,这将工作:
render: function() { return ( <ListView dataSource={this.state.dataSource} renderRow={(rowData) => { var inputRefs = []; var _focusInput = function(name) { inputRefs[name].focus(); }; var input1 = <TextInput ref={(input) => { inputRefs['input1'] = input; }} onSubmitEditing={_focusInput.bind(null, 'input2')} onEndEditing={_focusInput.bind(null, 'input2')} />; var input2 = <TextInput ref={(input) => { inputRefs['input2'] = input; }} />; return ( <View> {input1} {input2} </View> ); }}/> ); }
您可以在https://facebook.github.io/react- native/docs/textinput.html#content处深入研究TextInput事件。