MST
星途 面试题库

面试题:React高阶组件中条件渲染的基本实现方式

请阐述在React高阶组件中,如何通过条件渲染来决定是否渲染子组件。假设我们有一个高阶组件`withCondition`,它接收一个条件函数`conditionFn`,只有当`conditionFn`返回`true`时,被包裹的组件才会渲染,你需要用代码示例说明。
28.9万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试
import React from 'react';

// 高阶组件
const withCondition = (conditionFn) => (WrappedComponent) => {
    return (props) => {
        if (conditionFn(props)) {
            return <WrappedComponent {...props} />;
        }
        return null;
    };
};

// 示例子组件
const MyComponent = ({ message }) => {
    return <div>{message}</div>;
};

// 使用高阶组件包裹子组件
const ConditionalComponent = withCondition((props) => props.shouldRender)(MyComponent);

// 父组件
const ParentComponent = () => {
    const shouldRender = true;
    return <ConditionalComponent shouldRender={shouldRender} message="This is a conditional component" />;
};

export default ParentComponent;