集成redux后,react如何获取子组件的实例

子组件(在connect函数中加入参数forwardRef:true)

import React, { Component } from 'react'
import { Text, View ,FlatList,Image,RefreshControl } from 'react-native';
import styles from "./style";
import { TouchableHighlight } from 'react-native-gesture-handler';
import { connect } from "react-redux";
import { actions as newsAction,getData } from "../../../../redux/modules/newsPage/actions";
import { bindActionCreators } from 'redux';



class Newslist extends Component {


    scrollToTop = ()=>{
        this.refs.flat_list.scrollToOffset({
            offset:0,
            animated:false
        })
    }

   
    render() {
       
        const { news_list} = this.props.data;


        return (
          <View style={styles.box}> 
                <FlatList
                ref="flat_list" 
                data={news_list}
                renderItem={({item})=>{return <Text>{item.name}</Text>)}}
                keyExtractor={item=>item.news_id}         
                />
          </View>  
        )
    }
}

const mapStateToProps = (state)=>{ 
    return {
      data:getData(state)
    }
 }

 const mapDispatchToProps = (dispatch)=>{
    return {
        newsAction:bindActionCreators(newsAction,dispatch)
    }
 }

export default connect(mapStateToProps,mapDispatchToProps,null,{forwardRef:true})(Newslist);

父组件(子组件设置了forwardRef:true之后,父组件就可以通过ref获取到子组件的实例,调用子组件的方法或者获取子组件的数据)

import React, { Component } from 'react'
import {Text} from "react-native";
import SafeAreaViewPlus from "../../components/safeAreaViewPlus";
import global from "../../style";
import NavigationBar from "../../components/navigationBar";
import NewsNav from "./components/newsNav";
import NewsList from "./components/newsList";
import { connect } from "react-redux";
import { actions as newsAction,getData } from "../../redux/modules/newsPage/actions";
import { bindActionCreators } from 'redux';

class NewsPage extends Component {


    selType = ()=>{
      this.refs.child.scrollToTop();
    }

    render() {
        return (
        <SafeAreaViewPlus topColor={global.themeColor}>
            <NavigationBar hide={true}/>
            <NewsNav selType={this.selType}/>
            <NewsList ref="child"/>
        </SafeAreaViewPlus>
        )
    }
}


const mapStateToProps = (state)=>{ 
    return {
      data:getData(state)
    }
 }

 const mapDispatchToProps = (dispatch)=>{
    return {
        newsAction:bindActionCreators(newsAction,dispatch)
    }
 }

export default connect(mapStateToProps,mapDispatchToProps)(NewsPage);
发布了20 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/brokenkay/article/details/102668729