Javascript 如何将对象数组映射到React中的不同组件道具?
我在experience.js中有一个对象数组,如下所示: [ {全名:'vocab实验',简称:'vocab',…}, {全名:'思维实验',简称:'思维',…}, {全名:'whichenglish实验',简称:'whichenglish',…},Javascript 如何将对象数组映射到React中的不同组件道具?,javascript,reactjs,Javascript,Reactjs,我在experience.js中有一个对象数组,如下所示: [ {全名:'vocab实验',简称:'vocab',…}, {全名:'思维实验',简称:'思维',…}, {全名:'whichenglish实验',简称:'whichenglish',…}, ]; 由于需要将每个数组元素渲染到不同的组件,因此不能真正使用array::map,因为这更适合于将数组映射到同一组件 <Vocab data={vocabProps} img={require('...')}/> <Mind
]; 由于需要将每个数组元素渲染到不同的组件,因此不能真正使用array::map,因为这更适合于将数组映射到同一组件
<Vocab data={vocabProps} img={require('...')}/>
<Mind data={mindProps} />
<WhichEnglish data={whichenglishProps} />
给定实验阵列
const experiments = [
{ fullName: 'vocab Experiment', shortName: 'vocab', ......},
{ fullName: 'mind Experiment', shortName: 'mind', ......},
{ fullName: 'whichenglish Experiment', shortName: 'whichenglish', ......},
];
可以使用数组分解将每个元素保存到命名变量中
const [vocab, mind, whichEnglish] = experiments;
然后将每一个都摊铺到适当的组件中
<Vocab
id={vocab.shortName}
title={vocab.fullName}
duration={vocab.duration}
post={vocab.tagline}
img={require('../assets/images/quiz/Vocab.png')}
/>
<Mind
id={mind.shortName}
title={mind.fullName}
duration={mind.duration}
post={mind.tagline}
img={...}
/>
<WhichEnglish
id={whichEnglish.shortName}
title={whichEnglish.fullName}
duration={whichEnglish.duration}
post={whichEnglish.tagline}
img={...}
/>
我认为您可以使用数组方法实现这一目的,并根据短名称为每个实验获取精确的对象,如:
只需在道具上使用扩展语法,如:
<Vocab {...vocabProps} />
<Mind {...mindProps} />
<WhichEnglish {...whichenglishProps} />
给定
鉴于列表中可以有任意数量的对象,我将使用if语句,如下所示:
{experiments.map(e => {
if (e.shortName === 'vocab') {
return (<Vocab
id={e.shortName}
title={e.fullName}
duration={e.duration}
post={e.tagline}
img={require('../assets/images/quiz/Vocab.png')}
key={e.shortName}
/>)
} else if (e.shortName === 'mind') {
return <Mind ... />
} else if (e.shortName === 'whichenglish') {
return <WhichEnglish ... />
} else return null; // keep react happy
})}
这就是你要找的吗
const ComponentByType = {
vocab: Vocab,
mind: Mind,
whichEnglish: WhichEnglish
}
//...
{experiments.map(e => {
const type = someHowToGetType(e)
const Component = ComponentByType[type]
return (<Component key={e.shortName} {{...e}}/>)
})}
您已将道具传递给Vocab。这里有什么问题?@palaѕѕѕѕ所以我想把数组中的第一个对象传递给,第二个对象传递给,第三个对象传递给ok,所以在实验数组中总是有最多3个对象,或者它也可以比这个少?@rui你想要
{experiments.map(e => {
if (e.shortName === 'vocab') {
return (<Vocab
id={e.shortName}
title={e.fullName}
duration={e.duration}
post={e.tagline}
img={require('../assets/images/quiz/Vocab.png')}
key={e.shortName}
/>)
} else if (e.shortName === 'mind') {
return <Mind ... />
} else if (e.shortName === 'whichenglish') {
return <WhichEnglish ... />
} else return null; // keep react happy
})}
const ComponentByType = {
vocab: Vocab,
mind: Mind,
whichEnglish: WhichEnglish
}
//...
{experiments.map(e => {
const type = someHowToGetType(e)
const Component = ComponentByType[type]
return (<Component key={e.shortName} {{...e}}/>)
})}