JavaScript/react/条件渲染:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
创建页面,内容为“== 引言 == == IF/ELSE == <syntaxhighlight lang="javascript"> function render() { if (condition) { return <Component />; } else { return null; } }</s…”
 
Kangkk​(留言 | 贡献)
 
(未显示同一用户的9个中间版本)
第4行: 第4行:
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
function render() {
function render() {
   if (condition) {
   if (condition) return <Component />;
    return <Component />;
   else return null;
   } else {
    return null;
  }
}</syntaxhighlight>
}</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>
== do {} ==
== switch ==
<syntaxhighlight lang="javascript">
function render() {
  return <>
    {
      (()=> {
        switch (condition) {
          case 1: return <Component1 />;
          case 2: return <Component2 />;
          default: null;
        }
      })()
    }
  </>;
}</syntaxhighlight>
== Enums objects ==
<syntaxhighlight lang="javascript">
const Components = Object.freeze({
  save: <Component1 />,
  edit: <Component2 />
});
function render() {
  const action = condition ? "save" : "edit":
  return <>
    {Components(action))}
  </>;
}
</syntaxhighlight>
== 参考 ==
* [https://blog.logrocket.com/conditional-rendering-in-react-c6b0e5af381e/#ifelse Conditional rendering in React: 9 methods with examples]