在react-native中如何使用refs获取多级组件

时间:2016-07-01 08:44:29

标签: reactjs react-native refs

在componentDidMount函数中我可以使用this.refs [' test']获取此组件,但使用this.refs [' list']会出错。我尝试使用' ref = {list => {this.list = list}'为组件添加参考,并使用' this.list'得到组件,它也是一个错误。那么我可以获得该组件。

return(
  <View style={MainStyles.body}>
    <TopView selectAll={() => this._selectAll()} />
    <TabView ref={(ref) => this.tabView = ref}
      switchTab={(index) => this._switchTab(index)}/>
    <MyListView style={MainStyles.listView}
      ref='test'
      refresh={(okCall, failCall) => this._refresh(this, okCall, failCall)}
      loadMore={(okCall,failCall) => this._loadMore(this, okCall, failCall)}
      />
    <PageView style={MainStyles.content}
      ref={viewPager => { this.viewPager = PageViewWrapper(viewPager)}}
      onPageSelected={(e) => this._onPageSelected(e, this)}
      >
      <MyListView style={MainStyles.listView}
        ref='list'
        refresh={(okCall, failCall) => this._refresh(this, okCall, failCall)}
        loadMore={(okCall,failCall) => this._loadMore(this, okCall, failCall)}
        />
      <MyListView style={MainStyles.listView}
        ref={(ref) => this.myList1 = ref}
        refresh={(okCall, failCall) => this._refresh(this, okCall, failCall)}
        loadMore={(okCall,failCall) => this._loadMore(this, okCall, failCall)}
        />
    </PageView>
 </View>
)

1 个答案:

答案 0 :(得分:0)

您可以尝试这样this.refs.testthis.refs.list

检查下面的代码,它对我来说非常有用。

class sample extends Component {

componentDidMount() {
  console.log(this.refs.mainView);
  console.log(this.refs.welcomeText);
  console.log(this.refs.startedText);
  console.log(this.refs.secondView);
  console.log(this.refs.runText);
  console.log(this.refs.thirdView);
}

  render() {
   return (
     <View ref='mainView' style={styles.container}>
       <Text ref='welcomeText' style={styles.welcome}>
         Welcome to React Native!
       </Text>
       <Text ref='startedText' style={styles.instructions}>
        To get started, edit index.ios.js
       </Text>
       <View ref='secondView'>
         <Text ref='runText' style={styles.instructions}>
           Press Cmd+R to reload,{'\n'}
           Cmd+D or shake for dev menu
         </Text>
       </View>
       <View ref='thirdView' />
     </View>
   );
 }
}