我想我错过了一些关于如何在 Typescript 中使用 && 检查真实值的基本知识。
为什么 props.function 在 test1 中仍然是未定义的,并且必须像我在 test2 中那样进行检查。
import React from "react";
interface PropsModel {
label?: string
function?: Function,
}
function test1(props: PropsModel) {
return (
<div>
{props.label && <p>{props.label}</p>} // props.label is checked for undefined
{props.function && <button onClick={() => props.function()}>Dummy button</button>} // props.function is not checked for undefined
</div>
)
}
function test2(props: PropsModel) {
return (
<div>
{props.label && <p>{props.label}</p>} // props.label is checked for undefined
{props.function && <button onClick={() => {if (props.function) props.function()}}>Dummy button</button>} // props.function is checked for undefined
</div>
)
}
编辑 1:添加到操场的链接