如何在react render函数中创建动态href? [英] How to create dynamic href in react render function?

查看:41
本文介绍了如何在react render函数中创建动态href?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在渲染帖子列表.对于每篇文章,我都希望呈现一个带有该文章ID的锚标记,作为href字符串的一部分.

I am rendering a list of posts. For each post I would like to render an anchor tag with the post id as part of the href string.

render: function(){
    return (
        <ul>
            {
                this.props.posts.map(function(post){
                    return <li key={post.id}><a href='/posts/'{post.id}>{post.title}</a></li>
                })
            }
        </ul>
    );

我该如何做,以使每个帖子都具有/posts/1 /posts/2 等的href?

How do I do it so that each post has href's of /posts/1, /posts/2 etc?

推荐答案

使用字符串串联:

href={'/posts/' + post.id}

JSX语法允许使用字符串或表达式({...})作为值.您不能将两者混用.顾名思义,您可以在表达式内部使用任何JavaScript表达式来计算值.

The JSX syntax allows either to use strings or expressions ({...}) as values. You cannot mix both. Inside an expression you can, as the name suggests, use any JavaScript expression to compute the value.

这篇关于如何在react render函数中创建动态href?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆