В React Native, как настроить массив текста предупреждений с помощью FlatList
В react native, как настроить массив текста предупреждений с помощью FlatList.
В случае, если щелкнет первый элемент, я хочу показать "Сначала оповещение" в заголовке оповещения.
Но сложно синхронизировать идентификатор между ALERT_TITLE и props{id}.
После многократного сбоя мне требуется переполнение стека.
ответьте пожалуйста на мой вопрос.
Ниже мой код и ссылка из https://reactnative.dev/docs/0.60/flatlist
Я не уверен, что const array set const ALERT_TITLE = {'Alert First', 'Alert Second', 'Alert Third'}; или const ALERT_TITLE = [{id: 'aa', title: 'Alert First ',},{id: 'bb', title: 'Alert Second ',},{id: 'cc', title: 'Alert Third ",},];
const ALERT_TITLE = [
{id: 'aa', title: 'Alert First ',},
{id: 'bb', title: 'Alert Second ',},
{id: 'cc', title: 'Alert Third ',},
];
const ALERT_MESSAGE = [
{id: 'aa', title: 'msg First ',},
{id: 'bb', title: 'msg Second ',},
{id: 'cc', title: 'msg Third ',},
];
const DATA = [
{id: 'aa', title: 'First Item',},
{id: 'bb', title: 'Second Item',},
{id: 'cc', title: 'Third Item',},
];
function Item({ id, title, selected, onSelect }) {
return (
<TouchableOpacity
onPress={() => Alert.alert(
ALERT_TITLE.toDoSomeThing,//{if first item click I wanna show 'Alert First'}
ALERT_MESSAGE.toDoSomeThing,//{if first item click I wanna show 'msg First'}
[
{ text: 'Cancel'},
{ text: 'OK', onPress: () => onSelect(id)}
],
{ cancelable: false }
)}
style={[
styles.item,
{ backgroundColor: selected ? '#6e3b6e' : '#f9c2ff' },
]}
>
<Text style={styles.title}>{title}</Text>
</TouchableOpacity>
);
}
export default function App() {
const [selected, setSelected] = React.useState(new Map());
const onSelect = React.useCallback(
id => {
const newSelected = new Map(selected);
newSelected.set(id, !selected.get(id));
setSelected(newSelected);
},
[selected],
);
return (
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={({ item }) => (
<Item
id={item.id}
title={item.title}
selected={!!selected.get(item.id)}
onSelect={onSelect}
/>
)}
keyExtractor={item => item.id}
extraData={selected}
/>
</SafeAreaView>
);
}
1 ответ
ALERT_MESSAGE и ALERT_TITLE - это массивы, поэтому они не предоставляют обработчиков ALERT_TITLE.toDoSomeThing или ALERT_MESSAGE.toDoSomeThing.
Чтобы отобразить желаемый текст, вы должны найти нужный элемент в массивах ALERT_TITLE и ALERT_MESSAGE и получить доступ к полям из них, например
function Item({ id, title, selected, onSelect }) {
return (
<TouchableOpacity
onPress={() => Alert.alert(
ALERT_TITLE.find(el => el.id === id).title,//{if first item click I wanna show 'Alert First'}
ALERT_MESSAGE.find(el => el.id === id).title,//{if first item click I wanna show 'msg First'}
[
{ text: 'Cancel'},
{ text: 'OK', onPress: () => onSelect(id)}
],
{ cancelable: false }
)}
style={[
styles.item,
{ backgroundColor: selected ? '#6e3b6e' : '#f9c2ff' },
]}
>
<Text style={styles.title}>{title}</Text>
</TouchableOpacity>
);
}
Другой способ (который быстрее, чем этот) - передать индекс элемента компоненту Item, например:
Ваше объявление плоского списка станет:
<FlatList
data={DATA}
renderItem={({ item, index }) => (
<Item
id={item.id}
title={item.title}
selected={!!selected.get(item.id)}
onSelect={onSelect}
index={index}
/>
)}
keyExtractor={item => item.id}
extraData={selected}
/>
и ваш компонент Item получает индекс через props
function Item({ id, title, selected, onSelect, index }) {
return (
<TouchableOpacity
onPress={() => Alert.alert(
ALERT_TITLE[index].title,//{if first item click I wanna show 'Alert First'}
ALERT_MESSAGE[index].title,//{if first item click I wanna show 'msg First'}
[
{ text: 'Cancel'},
{ text: 'OK', onPress: () => onSelect(id)}
],
{ cancelable: false }
)}
style={[
styles.item,
{ backgroundColor: selected ? '#6e3b6e' : '#f9c2ff' },
]}
>
<Text style={styles.title}>{title}</Text>
</TouchableOpacity>
);
}