JavaScript/react/条件渲染:修订间差异
来自康健生活
| 第29行: | 第29行: | ||
function render() { | function render() { | ||
return <> | 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> | }</syntaxhighlight> | ||