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;