【发布时间】:2018-12-02 17:54:39
【问题描述】:
我正在尝试在 React 中使用 <Conditional if={condition}> 组件,该组件仅在条件为真时才呈现其内容。
我使用了来自 here 的代码,正如 Broda Noel 对 this question 的回复中所述。您还可以看到代码here。
import * as React from 'react';
const Conditional = props => (
!!props.if && props.children
);
class Item extends React.Component {
render() {
const item = { id: 2 };
return (
<>
<h2>Item detail</h2>
{/* Display item.foo.name if `foo` property exists */}
<Conditional if={item.foo}>
{item.foo.name}
</Conditional>
</>);
}
}
export default Item;
失败并出现错误:
Uncaught TypeError: Cannot read property 'name' of undefined
我知道我也可以使用{item.foo && item.foo.name},但是当代码变得更复杂时,我发现Conditional 的使用更具可读性。最重要的是,我真的很想了解这里发生了什么。
为什么 React 会渲染 Conditional 的内容,即使是条件为假? 有没有办法更改条件组件以使其在这种情况下工作?
我正在使用带有 typescript 的 React 16.4.1。
【问题讨论】:
-
尝试将if设置为
if={item.foo !== undefined}。你的 if 没有条件、比较或类似的东西。
标签: reactjs typescript