屏幕尺寸更改时强制在FlatList上重新渲染

时间:2017-12-13 15:46:34

标签: react-native native-base

我想在React Native中制作一个响应式应用程序。我使用以下命令在容器中订阅了Dimension更改:

const RCTDeviceEventEmitter = require("RCTDeviceEventEmitter");

export interface Props {
    data: Array<any>;
}

export interface State {}

class MyContainer extends React.Component<Props, State> {

    _updateIfSelected() {
        if (...some more logic...) {
            this.forceUpdate();
        }
    }

    constructor(props) {
        super(props);
        this.state = {
            listener: null,
            updateIfSelected: this._updateIfSelected.bind(this),
        };
    }

    componentWillMount() {
        this.setState({
            listener: RCTDeviceEventEmitter.addListener("didUpdateDimensions", this.state.updateIfSelected),
        });
    }

    componentWillUnmount() {
        this.state.listener.remove("didUpdateDimensions",this.state.updateIfSelected);
    }

    renderItem() {
        console.log("Rerendering Item")
        return <Text style={{ width: Dimensions.get("window").width }} >Some Text</Text>
    }

    render() {
        return (
            <FlatList
                data={this.props.data}
                keyExtractor={(_, i) => (i.toString())}
                renderItem={({item}) => this.renderItem(item)}
            />
    }
}

我想知道如何强制FlatList重新渲染其项目,因为当屏幕倾斜时外观需要改变。但是,由于数据没有变化,因此列表不会在屏幕倾斜时重新呈现。

文档提供了一个名为extraData的参数:

By passing extraData={this.state} to FlatList we make 
sure FlatList itself will re-render when the state.selected 
changes. 
Without setting this prop, FlatList would not know it 
needs to re-render any items because it is also a 
PureComponent and the prop comparison will not show any changes

但我真的不明白这是想说些什么。任何想法我如何在Dimension上更改FlatList Rerender?

1 个答案:

答案 0 :(得分:3)

您可以将函数传递给onLayout,并在调用onLayout时检查尺寸。我建议将该函数传递给父视图。然后你可以在函数

中设置state
class MyComponent extends Component {
  _onLayout() { // I haven't tried this but I think this or something similar will work

    const { width, height } = Dimensions.get('window');

    if(width > height) {
      this.setState(state => ({ ...state, orientation: 'landscape' }));
    } else {
      this.setState(state => ({ ...state, orientation: 'portrait' }));
    }
  }
  render() {
    return (
      <View onLayout={this._onLayout}>
      <FlatList
        data={this.props.data}
        keyExtractor={(_, i) => (i.toString())}
        renderItem={({item}) => this.renderItem(item)}
        extraData={this.state.orientation}
      />
      </View>
    )
  }
}