简体   繁体   中英

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. This tutorial hard-codes it for simplicity.

I can't do this in the JS itself: <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?

<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:

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

The following code is actually done in the cshtml razor page. It is rendering the CommentBox component to the content div

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

Since it is in the cshtml you can do this:

<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:

CSHTML:

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

External JS:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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