Refactor pressItem

Summary:
Changelog:
[General][Changed] - Refactor pressItem, a RNTester util for list based components to not pass state around.

Reviewed By: nadiia

Differential Revision: D25986318

fbshipit-source-id: d0dd85f783a83f73f83cfb1bd19d144c37af9ef9
This commit is contained in:
Luna Wei
2021-01-22 13:47:49 -08:00
committed by Facebook GitHub Bot
parent 335f6de00a
commit d0a455b3c3
4 changed files with 39 additions and 15 deletions
@@ -225,18 +225,9 @@ function getItemLayout(
return {length, offset: (length + separator) * index + header, index};
}
function pressItem(context: Object, key: string) {
const index = Number(key);
const pressed = !context.state.data[index].pressed;
context.setState(state => {
const newData = [...state.data];
newData[index] = {
...state.data[index],
pressed,
title: 'Item ' + key + (pressed ? ' (pressed)' : ''),
};
return {data: newData};
});
function pressItem(item: Item): Item {
const title = `Item ${item.key}${!item.pressed ? ' (pressed)' : ''}`;
return {...item, title, pressed: !item.pressed};
}
function renderSmallSwitchOption(
@@ -281,10 +281,21 @@ class FlatListExample extends React.PureComponent<Props, State> {
);
}
};
_pressItem = (key: string) => {
this._listRef && this._listRef.recordInteraction();
pressItem(this, key);
const index = Number(key);
const itemState = pressItem(this.state.data[index]);
this.setState(state => ({
...state,
data: [
...state.data.slice(0, index),
itemState,
...state.data.slice(index + 1),
],
}));
};
_listRef: React.ElementRef<typeof Animated.FlatList>;
}
@@ -167,8 +167,18 @@ class MultiColumnExample extends React.PureComponent<
);
}
};
_pressItem = (key: string) => {
pressItem(this, key);
const index = Number(key);
const itemState = pressItem(this.state.data[index]);
this.setState(state => ({
...state,
data: [
...state.data.slice(0, index),
itemState,
...state.data.slice(index + 1),
],
}));
};
}
@@ -286,7 +286,19 @@ class SectionListExample extends React.PureComponent<{...}, $FlowFixMeState> {
};
_pressItem = (key: string) => {
!isNaN(key) && pressItem(this, key);
if (isNaN(key)) {
return;
}
const index = Number(key);
const itemState = pressItem(this.state.data[index]);
this.setState(state => ({
...state,
data: [
...state.data.slice(0, index),
itemState,
...state.data.slice(index + 1),
],
}));
};
}