react native FlatList内嵌自己的Component不刷新的处理

问题描述:

原先列表里头有多个自定义标签,部分是放到FlatList所在类里头的,内部class, 当列表刷新,元素数量变化时,没有影响。

但其中有一个自定义组件包含state 最后造成,元素个数变化后,异步先按顺序获取这个组件旧的虚拟Dom,造成新的Flatlist元素渲染时,对应包含的自定义组件没有重新创建而是用旧的遍历返回对应的旧虚拟节点。

最后的实现方式如下:也就是实现显示'更多'的效果

因为这样之后没有完整的state 而不会有异步渲染子节点,而是跟随FlatList同步生成渲染 keyExtractor={(item, index) => item.id}
之前一直是用index 做键来关联,后面用元素的id唯一索引就ok 了老了么......

import React, { Component } from 'react';
import {
    Text
} from 'react-native';
import {size} from "../util/style";
const sz = size.width/375;

export default class HaveMoreText extends Component {
    constructor(props){
        super(props)
        this.state = {
            content:this.props.content,
            showMore:false
        }
    }

    render(){
        return(
             <Text 
                onLayout={(e)=>{
                    let layout = e.nativeEvent.layout;
                    // console.log(layout.height)
                    // console.log(layout)
                    // console.log(this.refs.text)
                    if(layout.height>3*22.4*sz){//行高是20然后把text的高度设置为60就能保证行数控制在3行
                        // this.refs.text.props.children[0]
                        let newContent = this.state.content.substring(0,parseInt(this.state.content.length*3*22.4*sz/layout.height)-10)
                        this.setState({showMore:true,content:newContent+'...'})
                //         this.refs.text.setNativeProps({
                //             numberOfLines:3
                //         });
                    }
                }}
                ref='text'
                //numberOfLines={3}
                style={{ color:'#767A7F',fontSize:14*sz, fontFamily:'OpenSans',lineHeight:22.4*sz }}>
                { this.state.content }
                {this.state.showMore?<Text style={{color:'#56C2F2',fontSize:14*sz, fontFamily:'OpenSans',lineHeight:22.4*sz,position:'absolute',right:0}}>more</Text>:null}
            </Text>
        )
    }
}
复制代码

转载于:https://juejin.im/post/5cf59df96fb9a07eee5eb97e

猜你喜欢

转载自blog.csdn.net/weixin_33849215/article/details/91416996