[英](React Native) Displaying a list of cards for items in an array
我有两个数组,假设单词和定义
export default class Dictionary extends React.Component { constructor(props) { super(props); this.state = { word: [], definition:[], index: 0 }; }
我有一个道具
<Card word = {w} definition = {d}/>
我想为阵列中每个单词/定义对显示这些卡的列表。 如果有5个单词/定义,那么我希望其中5张卡片显示在ScrollableView中。 我怎样才能做到这一点? 谢谢!
您可以使用Array.prototype.map
函数Array.prototype.map
函数的回调中的第二个参数是index。 您可以使用该索引来显示相应的definition
项,如下所示
export default class Dictionary extends React.Component {
constructor(props) {
super(props);
this.state = {
word: ["a","b","c"],
definition:["a","b","c"],
index: 0
};
render() {
<div>
{this.state.word.map((w,i) => {
return <Card word = {w} definition = {this.state.definition[i]}/>
})}
</div>
}
}
在您的状态下,您可以将单词和定义合并为一件事,例如:
dictionary: [
{
index: 0,
word: 'Car',
definition: 'Definition of car',
},
// More objects like the one above
]
然后编写一个呈现此对象数组的函数,可能像这样:
renderDictionary() {
return (this.state.dictionary.map(word => {
<Card key={word.index} word={word.word} definition={word.definition} />
}));
}
然后,您只需调用该函数:
export default class Dictionary extends React.Component {
constructor(props) {
super(props);
this.state = {
dictionary: [
{
index: 0,
word: 'Car',
definition: 'Definition of car',
},
// More objects like the one above.
],
};
}
renderDictionary() {
return (this.state.dictionary.map(word => {
<Card key={word.index} word={word.word} definition={word.definition} />
}));
}
render () {
return (
<View>
{this.renderDictionary()}
</View>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.