我有一个难题。
我有想要在组件中切换的文本。
基本上true
=> 勾选
和false
=> 取消勾选
但我想要第三种情况,我不想显示任何文本
如果我不将 prop 传递给该组件,它会自动假设为 true。我可以传递 propName={null} 或类似的东西吗?
或者我是否必须将其提取到一个函数中(我宁愿不这样做)
最佳答案
如果您不向组件提供 prop,它将不会出现在该组件内表示 props 的对象中。因此,您可以检查该 prop 是否已定义:
const Component = (props) => {
if (props.checked === undefined) {
return <Something />;
}
return <SomethingElse someProp={props.checked} />;
};
然后,这将渲染Something
:
<Component />
这些都将渲染 SomethingElse
:
<Component checked />
<Component checked={true} />
<Component checked={false} />
关于javascript - 如何在 React 中将 prop 作为 null 传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50288687/