You need to enable JavaScript to run this app. React+TS报错Type '() => Element'不可赋值给类型'string'如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

React+TS报错Type '() => Element'不可赋值给类型'string'如何解决?

问题修复方案

报错原因

  • 你在调用answers.map时,将传入的回调函数命名为了answer,且没有接收map方法默认传入的当前遍历元素参数。此时回调函数内部访问的answer实际是这个函数本身,类型为() => Element,而dangerouslySetInnerHTML.__html需要传入string类型的值,类型不匹配触发报错。
  • 你之前将{{ __html: answer }}改为{{ answer }}的尝试无效,是因为此时answer仍然是函数对象,无论用哪种方式赋值都不符合类型要求。

修复代码

直接修改map遍历部分的逻辑,正确接收遍历得到的answer字符串即可,修改后的完整组件代码如下:

import { QuestionAnswerTwoTone } from "@material-ui/icons";
import React from "react";

// 定义props类型
type Props = {
  question: string;
  answers: string[];
  callback: any;
  userAnswer: boolean;
  questionNm: number;
  totalQuestions: number;
};

export default function QuestionCard({
  question,
  answers,
  callback,
  userAnswer,
  questionNm,
  totalQuestions,
}: Props) {
  return (<div>
      <p> Question :  {questionNm} / {totalQuestions} </p>
      <p dangerouslySetInnerHTML={{ __html: question }} />
      <div>
          {/* 修正map逻辑,接收遍历的每个answer元素作为参数 */}
          {answers.map((answer: string) => {
              return(<div key={answer}>
                <button disabled={userAnswer} onClick={callback}>
                    <span dangerouslySetInnerHTML={{ __html: answer }}/>
                </button>
            </div>);
          })}
      </div>
  </div>
  );
}

补充提示:React中遍历渲染列表时需要给每个列表项添加唯一的key属性,避免运行时警告,上述代码已添加该属性,若answer值不唯一,可使用map的第二个参数索引作为key。

内容的提问来源于stack exchange,提问作者Karol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 04:54:03