[英](React Native) Displaying a list of cards for items in an array
I have two arrays, let's say word and definition 我有两个数组,假设单词和定义
export default class Dictionary extends React.Component { constructor(props) { super(props); this.state = { word: [], definition:[], index: 0 }; }
I have a prop 我有一个道具
<Card word = {w} definition = {d}/>
and I want to display a list of these cards for each word/definition pair in the array. 我想为阵列中每个单词/定义对显示这些卡的列表。 If there are 5 words/definitions, then I want 5 of these cards to display in a ScrollableView. 如果有5个单词/定义,那么我希望其中5张卡片显示在ScrollableView中。 How can I do this? 我怎样才能做到这一点? Thanks! 谢谢!
You can uses Array.prototype.map
function.The second argument in Array.prototype.map
function's callback is index. 您可以使用Array.prototype.map
函数Array.prototype.map
函数的回调中的第二个参数是index。 You can use that index to display the corresponding definition
item like this 您可以使用该索引来显示相应的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>
}
}
In your state you could merge word and definition in one thing like: 在您的状态下,您可以将单词和定义合并为一件事,例如:
dictionary: [
{
index: 0,
word: 'Car',
definition: 'Definition of car',
},
// More objects like the one above
]
Then write a function that renders this array of objects, could be like: 然后编写一个呈现此对象数组的函数,可能像这样:
renderDictionary() {
return (this.state.dictionary.map(word => {
<Card key={word.index} word={word.word} definition={word.definition} />
}));
}
And then you just call the function: 然后,您只需调用该函数:
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.