我说有两个阵列 单词和定义
export default class Dictionary extends React.Component {
constructor(props) {
super(props);
this.state = {
word: [],
definition:[],
index: 0
};
}
我有一个道具
<Card word = {w} definition = {d}/>
我希望为数组中的每个字/定义对显示这些卡的列表。如果有5个单词/定义,那么我想要在ScrollableView中显示其中5个这样的卡片。我怎样才能做到这一点?谢谢!
答案 0 :(得分:2)
你可以使用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>
}
}
答案 1 :(得分:2)
在你所在的州,你可以合并单词和定义,例如:
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>
);
}
}