如何在 Typescript 中使用 SolidJS 的 <Show> 标签

问题描述 投票:0回答:3

我在 SolidJS 组件中有以下代码

<Show when={props.hint}>
   <HintText>{props.hint}</HintText>
</Show>

它按预期工作,但是打字稿一直说,而不是string

props.hint
也可以是undefined

我访问了https://www.solidjs.com/guides/typescript的文档,尝试使用“bang [ ! ]”运算符(又名非空断言运算符),尝试使用块内的函数,但是typescript 一直在抱怨。

*图片供参考:

有更好的方法吗?

javascript jsx show solid-js
3个回答
0
投票

您定义了 prop 参数是什么样的吗?如果不是,那么这可能就是问题所在。下面我有一个示例,说明它可能是什么样子:

const Hint: Component<{hint: string}> = (props) => {
  return (
    <Show when={props.hint}>
      <p>{props.hint}</p>
    </Show>
  )
}

0
投票

indevsmiles 关于组件属性的输入是正确的。

但是,如果变量可能未定义,您可以使用 Show 的 keyed-attribute。这将返回一个 NonNullable 对象。

const [something, setSomething] = createSignal<string | undefined>();

<Show when={something()} keyed>{(variable) =>
   <b>{variable}</b>
}
</Show>

https://www.solidjs.com/docs/latest/api#show


0
投票

也许很难看,但这应该可以用 Nullish 合并运算符 (??):

解决问题
<Show when={props?.hint}>
  <HintText>{props?.hint ?? ''}</HintText>
</Show>
© www.soinside.com 2019 - 2024. All rights reserved.