如何在 Tooltip 的 title pro 中使用 if 语句返回字符串

How to use a if statement returning a string in Tooltip's title pro

我试图通过调用一个函数并使用 if 语句有条件地提供工具提示的标题,但我遇到了错误。

  const getStatusMessage = (answer: AnswerStatus) => {
if (answer == AnswerStatus.ANSWER_SUBMITTED || answer == AnswerStatus.ANSWER_PROCESSING) {
  return 'answers are still being processed.'
} else if (answer == AnswerStatus.QUESTION_SERVED) {
  return "question was given to candidate but didn't answer it."
} else if (answer == AnswerStatus.ANSWER_FAILED) {
  return 'there was a problem processing the answer of the candidate.'
}

}

<Tooltip placement='bottom-end' title={getStatusMessage(answer.status)}><button/></Tooltip>

---错误信息---

类型 'string | undefined' 不可分配给类型 'boolean | ReactChild | ReactFragment | ReactPortal'。

类型 'undefined' 不可分配给类型 'boolean | ReactChild | ReactFragment | ReactPortal'.ts(2322) Tooltip.d.ts(163, 3):预期类型来自 属性 'title' ,它在此处声明为类型 'IntrinsicAttributes & TooltipProps'

抛出错误是因为 Tooltip 组件的 title 属性正在获取值 undefined

当 answer.status 为 undefined 时,您没有涵盖默认情况。

所以要么

<Tooltip placement='bottom-end' title={answer.status? getStatusMessage(answer.status) : '' }><button/></Tooltip>

或您的 getStatusMessage 中的 return ''; 语句即可。

  const getStatusMessage = (answer: AnswerStatus) => {
if (answer == AnswerStatus.ANSWER_SUBMITTED || answer == AnswerStatus.ANSWER_PROCESSING) {
  return 'answers are still being processed.'
} else if (answer == AnswerStatus.QUESTION_SERVED) {
  return "question was given to candidate but didn't answer it."
} else if (answer == AnswerStatus.ANSWER_FAILED) {
  return 'there was a problem processing the answer of the candidate.'
}
return '';