简体   繁体   English

将Url.Action传递到React JSX文件?

[英]passing a Url.Action to a react JSX file?

This tutorial says: 本教程说:

Note that in a real app, you should generate the URL server-side (via Url.Action call) and pass it down, or use RouteJs rather than hard-coding it. 请注意,在真实的应用程序中,您应该生成URL(通过Url.Action调用)在服务器端并将其传递下来,或者使用RouteJ而不是对其进行硬编码。 This tutorial hard-codes it for simplicity. 为了简单起见,本教程对其进行了硬编码。

I can't do this in the JS itself: <CommentBox url="@Url.Action("Comments")" />, 我无法在JS本身中做到这一点: <CommentBox url="@Url.Action("Comments")" />,

... so what does it mean by "pass it down"? ...那么“传递下去”是什么意思?

Is that just another way of saying "define the URL inside a Razor csHtml file where using @ is allowed," like this? 是否只是这样说“在允许使用@的Razor csHtml文件中定义URL,”这样的另一种说法?

<script>
   $.CommentsUrl = '@this.Url.Action("Comments", "Home")';
<script>

... or is there a better way? ... 或者,还有更好的方法?

Even when I do the latter, that doesn't help me get the URL into this piece of code: 即使我做后者,也无济于事把URL插入这段代码中:

ReactDOM.render(
    <CommentBox url=??? />,
    document.getElementById('content')
);

The following code is actually done in the cshtml razor page. 以下代码实际上是在cshtml剃刀页面中完成的。 It is rendering the CommentBox component to the content div 它将CommentBox组件呈现到内容div

ReactDOM.render(
    <CommentBox url=??? />,
    document.getElementById('content')
);

Since it is in the cshtml you can do this: 由于它在cshtml中,因此您可以执行以下操作:

<div id="content"></div>
<script type="text/javascript">
    ReactDOM.render(
        <CommentBox url='@Url.Action("Comments")' />,
        document.getElementById('content')
    );
</script>

If you are only including a js file then you would need to create a global javascript variable and use it: 如果仅包括一个js文件,则需要创建一个全局javascript变量并使用它:

CSHTML: CSHTML:

<div id="content"></div>
<script type="text/javascript">
    var commentUrl = '@Url.Action("Comments")';
</script>

External JS: 外部JS:

ReactDOM.render(
    <CommentBox url={commentUrl} />,
    document.getElementById('content')
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM