
[英]Can conditional rendering in React use logical operator || when rendering the same content?
[英]Does if / else do the same thing as ternary and logical && operator in React conditional rendering
我有一个 React 组件,如果show
为true
,它会显示另一个组件:
const ChildComponent = ({ show }: Props) => {
if (show) {
return <AnotherChild />;
}
return null;
};
上面的 if/else 与三元运算符或 && 的作用相同:
三元:
return show ? (
<AnotherChild />;
) : null
逻辑 && 运算符:
返回({显示&&});
如果show
始终是 boolean,那么是的,这些都是等价的。
如果show
是假的但不是null
也不是undefined
,可能会有一点问题,因为它会被渲染,例如:
const App = ({ show }) => { return show && <div>content</div>; }; ReactDOM.createRoot(document.querySelector('.react')).render(<App show={0} />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <div class='react'></div>
如果 prop 的类型不受约束,最好使用条件运算符或if
/ else
显式替换null
而不是使用&&
。 (不过貌似你用的是TypeScript,所以类型受限,这样就好了)
问题未解决?试试以下方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.