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

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
第29行: 第29行:
function render() {
function render() {
   return <>
   return <>
     {
     {(() => (condition ? <Component /> : null))();}
      (() => (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>
}</syntaxhighlight>

2022年6月8日 (三) 11:20的版本

引言

IF/ELSE

function render() {
  if (condition) return <Component />;
  else return null;
}

三目运算符

function render() {
  return condition ? <Component /> : null;
}

&&

function render() {
  return condition && <Component />;
}
某些场景下 condition = false 是,会将 false 以字符串形式输出到页面中。

IIFE

function render() {
  return <>
    {(() => (condition ? <Component /> : null))();}
  </>;
}

子组件

function render() {
  return <>
    <Sub />
  </>;
}
function Sub() {
  return condition ? <Component /> : null;
}

IF 组件

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;
}

高阶组件

function HOC(Component) {
  return function EC(props) {
    if (condition) return <Component {...props} />;
    return <Component2 {...props} />;
  };
}