javascript - 如何访问 SectionList 的数据?
问题描述
我正在尝试使用一些数据创建动态 SectionList。我为我的问题创建了一个示例代码,这是我的数据:
const DATAS = [
(DATA1 = [
{
title: "A",
data: ["X", "Y", "Z"],
},
{
title: "B",
data: ["F", "O", "F"],
},
]),
(DATA2 = [
{
title: "M",
data: ["a", "r", "o"],
},
{
title: "T",
data: ["F", "s", "s"],
},
]),
];
export default DATAS;
我怎样才能访问 DATA1 或 DATA2,
import DATAS from .....
const Item = ({ title }) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
function MySectionList(props) {
return (
<SectionList
sections={//i have no idea }
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => <Item title={item} />}
renderSectionHeader={({ section: { title } }) => (
<Text style={styles.header}>{title}</Text>
)}
/>
);
}
我真的很困惑。我尝试了很多东西,但仍然无法正常工作。
解决方案
看起来sections={DATA[0]}
会工作。文档显示您必须将数组传递给sections
. 由于您DATAS
的导出为对象数组的数组,因此您需要选择要传递给组件的数组。
仅显示DATA1
:
function MySectionList(props) {
return (
<SectionList
sections={DATAS[0]}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => <Item title={item} />}
renderSectionHeader={({ section: { title } }) => (
<Text style={styles.header}>{title}</Text>
)}
/>
);
}
仅显示DATA1
并DATA2
作为一个列表:
function MySectionList(props) {
return (
<SectionList
sections={DATAS.flat()}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => <Item title={item} />}
renderSectionHeader={({ section: { title } }) => (
<Text style={styles.header}>{title}</Text>
)}
/>
);
}
注意:如果你想渲染DATA1
和DATA2
作为单独的SectionList
对象,你将不得不渲染每个对象到它们自己的列表的映射:
function MySectionList(props) {
const { dataLists } = props;
return (
<>
{
dataLists.map(dataList => (
<SectionList
sections={dataList}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => <Item title={item} />}
renderSectionHeader={({ section: { title } }) => (
<Text style={styles.header}>{title}</Text>
)}
/>
))
}
</>
);
}
MySectionList.propTypes = {
dataLists: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.instanceOf(Section)))
};
<MySectionList dataLists={DATAS} />
推荐阅读
- d3.js - 缺少 D3js 第一个刻度标签
- reactjs - 反应组件目录的命名约定
- c# - 在我的屏幕顶部打开时的 C# Chrome 驱动程序
- c - CMake - 始终构建特定文件
- log4j2 - 启用 SSL 的 log4j2 Socket Appender
- xamarin - Xamarin 窗体 DisplayActionSheet 外部触摸错误
- html - 如果不满足条件,有没有办法删除 HTML 中的链接?
- javascript - 如何使用由 Crypto 库加密的 CryptoJS 解密数据?
- delphi - 运算符不适用于此操作数类型 Delphi
- r - 多个 valueBoxes 的 SelectInput