我有两个数组,假设单词和定义
export default class Dictionary extends React.Component {
constructor(props) {
super(props);
this.state = {
word: [],
definition:[],
index: 0
};
}
我有一个道具
<Card word = {w} definition = {d}/>
我想为数组中的每个单词/定义对显示这些卡的列表。如果有 5 个单词/定义,那么我希望其中 5 张卡片显示在可滚动视图中。我该怎么做?谢谢!
您可以使用Array.prototype.map
函数。函数回调中的第二个参数是 index Array.prototype.map
。可以使用该索引显示相应的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>
);
}
}