【问题标题】:React Native- How can I call a function of a child view from its parent?React Native-如何从父视图调用子视图的函数?
【发布时间】:2016-09-19 10:33:45
【问题描述】:

我是 react native 的新手,遇到了这个问题。我有一个选项卡视图,其中 tabview.js 文件中有 2 个选项卡,tab1.js 和 tab2.js 用于 tab1 和 tab2。 因此,当页面加载两个选项卡时,componentDidMount 函数调用 loadData 函数,该函数从 web 获取数据。现在我想在更改选项卡时刷新数据。但是怎么在tabview.js里面调用tab1.js的loadData函数呢?

这是我正在使用的代码

tabview.js

render() {
 return (
    <View style={{flex: 1}}>
    <Header style={{flex: 1}} />
  <ScrollableTabView style={{flex: 10}} onChangeTab={(e)=>{this.checkTabPosition(e)}}>
    <Tab1 tabLabel="Tab1" navigator={this.props.navigator}/>
    <Tab2 tabLabel="Tab2" navigator={this.props.navigator} />
  </ScrollableTabView>
  </View>
 );
}

tab1.js

render() {
    return (
        <ScrollView refreshControl={
                    <RefreshControl
                        refreshing={this.state.refreshing}
                        onRefresh={this._onRefresh.bind(this)}
                    />
                }
                >
        <View>
            <ListView style={styles.listview}
                dataSource={this.state.dataSource}
                renderRow={(rowData) => <ListItem rowData={rowData} navigator={this.props.navigator} />}
                enableEmptySections={true}
            />
        </View>
        </ScrollView>
    );
}

componentDidMount(){
  this.fetchData();
}

tab2.js 中相同

【问题讨论】:

    标签: reactjs react-native ecmascript-6


    【解决方案1】:

    这是props 地狱问题;)。这就是为什么在 React 中,建议让您的状态尽可能地位于层次结构的上层,或者使用一些状态管理库:(Flux、Redux 等)。

    在您的情况下,您应该将标签数据移动到您的父组件TabView。然后你可以这样做:

    <Tab1 data={this.state.yourTab1Data} ... />
    <Tab2 data={this.state.yourTab2Data} ... />
    

    最后,您的 onChangeTab 应该调用您的刷新过程(可能是获取数据),当获取该数据时,您将在您的 TabView 组件中使用 setState 并且重新渲染将导致 data 道具传递给Tab1 和Tab2,这样你就会得到你想要的东西。

    基本上你需要从上到下工作。由于传递回调很痛苦,这就是为什么你可能想要使用状态管理库,当然,它是完全可选的。

    【讨论】:

    • 是的,我将使用 Redux。
    【解决方案2】:

    您必须在标签中添加ref,然后使用this.refs。您的代码将如下所示:

    checkTabPosition(e){
        // determine which tab to refresh
        var tabToRefresh = ...;
    
        // refresh tab
        refreshTab(tabToRefresh);
    }
    
    refreshTab( tab ){
      this.refs[tab].fetchData();
    }
    
    render() {
     return (
        <View style={{flex: 1}}>
           <Header style={{flex: 1}} />
           <ScrollableTabView style={{flex: 10}} onChangeTab={(e)=>    {this.checkTabPosition(e)}}>
              <Tab1 ref="tab1" tabLabel="Tab1" navigator={this.props.navigator}/>
              <Tab2 ref="tab2" tabLabel="Tab2" navigator={this.props.navigator} />
           </ScrollableTabView>
        </View>
     );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多