查看“︁JavaScript/react/条件渲染”︁的源代码
来自康健生活
←
JavaScript/react/条件渲染
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
== 引言 == == IF/ELSE == <syntaxhighlight lang="javascript"> function render() { if (condition) return <Component />; else return null; }</syntaxhighlight> == 三目运算符 == <syntaxhighlight lang="javascript"> function render() { return condition ? <Component /> : null; }</syntaxhighlight> == && == <syntaxhighlight lang="javascript"> function render() { return condition && <Component />; }</syntaxhighlight> <div class="pageBoxGreen">某些场景下 <code>condition = false</code> 是,会将 false 以字符串形式输出到页面中。</div> == IIFE == <syntaxhighlight lang="javascript"> function render() { return <> {(() => (condition ? <Component /> : null))();} </>; }</syntaxhighlight> == 子组件 == <syntaxhighlight lang="javascript"> function render() { return <> <Sub /> </>; } function Sub() { return condition ? <Component /> : null; } </syntaxhighlight> == IF 组件 == <syntaxhighlight lang="javascript"> function render() { return <If condition={true}> <Component /> </If>; } function If() { const condition = props.condition || false; const positive = props.then || null; const negative = props.else || null; // todo ... return condition ? positive : negative; } </syntaxhighlight> == 高阶组件 == <syntaxhighlight lang="javascript"> function HOC(Component) { return function EC(props) { if (condition) return <Component {...props} />; return <Component2 {...props} />; }; }</syntaxhighlight>
返回
JavaScript/react/条件渲染
。
导航菜单
康健生活
搜索
user-page
通知
user-interface-preferences
个人工具
登录
五一
多读书,多运动,多到远处走走,再看看不一样的世界。