我想在React Native中制作一个响应式应用。我使用以下方式订阅容器中的尺寸更改:
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)}
/>
}
}
我想知道如何迫使lantlist填充其物品,因为当屏幕倾斜时,外观需要更改。但是,由于数据不会更改,因此列表不会在屏幕倾斜上列出。
文档提供了一个称为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
,但我真的不明白这要说什么。有什么想法我如何使landlist rerender在维度上更改?
您可以将函数传递给onlayout,并在调用onlayout时检查尺寸。我建议将功能传递给父视图。然后,您可以在函数中设置
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>
)
}
}