react如何设置条件
条件渲染方法
在React中设置条件渲染可以通过多种方式实现,每种方式适用于不同场景。
三元运算符 适用于简单的条件判断,语法简洁:
{isLoggedIn ? <LogoutButton /> : <LoginButton />}
逻辑与运算符(&&) 适合条件成立时渲染单一组件:
{unreadMessages.length > 0 && <MessageList messages={unreadMessages} />}
条件分支处理
if-else语句 在组件函数体内使用传统条件语句:
function Greeting({ isLogin }) {
if (isLogin) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
立即执行函数 适合复杂条件逻辑:
{(() => {
if (error) return <ErrorComponent />;
if (loading) return <Loader />;
return <DataView />;
})()}
动态样式控制
className条件绑定 使用classnames库处理复杂类名逻辑:
import classnames from 'classnames';
<div className={classnames('button', { 'active': isActive })} />
行内样式条件 直接操作style对象:
<div style={{ display: shouldShow ? 'block' : 'none' }} />
高阶组件模式
HOC条件包装 创建可复用条件逻辑的高阶组件:
function withCondition(Component) {
return function WrappedComponent({ condition, ...props }) {
return condition ? <Component {...props} /> : null;
}
}
状态管理集成
Redux条件渲染 连接store状态进行条件判断:
const VisibleTodoList = connect(
state => ({
todos: selectVisibleTodos(state.todos, state.visibilityFilter)
}),
{ toggleTodo }
)(TodoList)
Context API条件 基于上下文值的条件渲染:
<ThemeContext.Consumer>
{theme => theme === 'dark' ? <DarkTheme /> : <LightTheme />}
</ThemeContext.Consumer>
性能优化技巧
记忆化组件 使用React.memo避免不必要的重渲染:
const MemoizedComponent = React.memo(function MyComponent({ dep }) {
return dep ? <ExpensiveComponent /> : null;
});
懒加载条件 动态导入配合条件渲染:

const OtherComponent = React.lazy(() => import('./OtherComponent'));
{showComponent && (
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
)}






