如何将带嵌套标签与条件的C# Razor代码转换为React.js代码
正确转换Razor条件渲染到React的方法
原始Razor代码
@if (isOnline == false) { <div class="container"> @if (ViewBag.IsLink1 == "True") { @Html.ActionLink("Link1", "Index", "Home1") } @if (ViewBag.IsLink == "True") { @Html.ActionLink("Link2", "Index", "Home2") } </div> } else { <p>this is P tag...</p> }
用户错误的React代码
<Sample isOnline={false} IsLink1="True" IsLink2={"True"} /> function Sample(props) { return (props.isOnline == false) ? <div className="container"> (props.IsLink1 == "True") ?<a href="/Home1/Index">Link1</a>:'' (props.IsLink2 == "True") ?<a href="/Home2/Index">Link2</a>:'' </div> : <p>this is P tag...</p> }
错误原因
在JSX中,直接书写JavaScript表达式会被当作普通文本渲染,必须用**大括号{}**包裹才能让React识别并执行这些逻辑。用户的嵌套三元表达式没有用大括号包裹,所以被直接输出成了文本。
正确的React转换代码
方法1:用大括号包裹三元表达式
<Sample isOnline={false} IsLink1="True" IsLink="True" /> function Sample(props) { return !props.isOnline ? ( <div className="container"> {props.IsLink1 === "True" ? <a href="/Home1/Index">Link1</a> : null} {props.IsLink === "True" ? <a href="/Home2/Index">Link2</a> : null} </div> ) : ( <p>this is P tag...</p> ); }
方法2:用&&短路求值简化判断(更简洁)
当条件为真时渲染元素,为假时返回false,React会忽略false、null、undefined这类值,不会渲染任何内容:
<Sample isOnline={false} IsLink1="True" IsLink="True" /> function Sample(props) { return !props.isOnline ? ( <div className="container"> {props.IsLink1 === "True" && <a href="/Home1/Index">Link1</a>} {props.IsLink === "True" && <a href="/Home2/Index">Link2</a>} </div> ) : ( <p>this is P tag...</p> ); }
方法3:提取逻辑到变量(更易维护)
如果判断逻辑复杂,可以提前把要渲染的元素提取到变量中:
<Sample isOnline={false} IsLink1="True" IsLink="True" /> function Sample(props) { let content; if (!props.isOnline) { const link1 = props.IsLink1 === "True" ? <a href="/Home1/Index">Link1</a> : null; const link2 = props.IsLink === "True" ? <a href="/Home2/Index">Link2</a> : null; content = ( <div className="container"> {link1} {link2} </div> ); } else { content = <p>this is P tag...</p>; } return content; }
内容的提问来源于stack exchange,提问作者Akbar Taghipour
相关产品推荐
相关产品推荐

