我需要根据数组中的值创建一个链接 ul。链接已创建,但 href
属性是随机分配的,与我传递给 getUrl
函数的实际值不对应。
这是迄今为止我的代码:
getURL (type) {
let url
switch (type) {
case 'Yahoo':
url = 'https://www.yahoo.com/'
case 'Bing':
url = 'https://www.bing.com/'
default:
url = 'https://www.google.com'
}
return url
}
和渲染:
render () {
let { expandList } = this.state
let listItems = [
'Google',
'Bing',
'Yahoo'
]
let list = expandList
? listItems.map((item, index) => {
return (
<li key={index}>
<a href={this.getURL(item)} target='_blank'>
{item}
</a>
</li>
)
})
: ''
return (
<div>
<ul>{list}</ul>
</div>
)
}
最佳答案
您需要在每个案例之后中断或从中返回。如果您不这样做,它将始终继续默认
,并返回 google 网址。
function getURL(type) {
switch (type) {
case 'Yahoo':
return 'https://www.yahoo.com/'
case 'Bing':
return 'https://www.bing.com/'
default:
return 'https://www.google.com'
}
}
console.log(getURL('Yahoo'));
console.log(getURL('Bing'));
关于javascript - 从项目数组动态创建链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49459692/