Javascript 如何在反应渲染函数中创建动态href?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31567729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:50:22  来源:igfitidea点击:

How to create dynamic href in react render function?

javascriptreactjs

提问by Connor Leech

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.

我正在渲染一个帖子列表。对于每个帖子,我想呈现一个带有帖子 ID 的锚标记作为 href 字符串的一部分。

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>
    );

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

如何做到这一点,使每个岗位有HREF的/posts/1/posts/2等等?

回答by Felix Kling

Use string concatenation:

使用字符串连接:

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

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.

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

回答by Nath

You can use ES6 backtick syntax too

您也可以使用 ES6 反引号语法

<a href={`/customer/${item._id}`} >{item.get('firstName')} {item.get('lastName')}</a>

More info on es6 template literals

有关 es6 模板文字的更多信息

回答by thalacker

In addition to Felix's answer,

除了菲利克斯的回答,

href={`/posts/${posts.id}`}

would work well too. This is nice because it's all in one string.

也会很好用。这很好,因为它都在一个字符串中。

回答by Khachornchit Songsaen

Could you please try this ?

你能试试这个吗?

Create another item in post such as post.linkthen assign the link to it before send postto the render function.

在 post 中创建另一个项目,例如post.link,然后在将post发送到渲染函数之前为其分配链接。

post.link = '/posts/+ id.toString();

So, the above render function should be following instead.

所以,上面的渲染函数应该跟随。

return <li key={post.id}><a href={post.link}>{post.title}</a></li>