【问题标题】:Type '() => Element' is not assignable to type 'string'类型“()=>元素”不可分配给类型“字符串”
【发布时间】:2021-07-29 20:03:38
【问题描述】:

问候!

我有一个常规的function,我返回一个span 和一个prop(如果我没记错的话)。 在我的 ts 代码上我有这个错误

Error image

这是我的代码。文件名为qCard.tsx

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

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

// A function statement declared component that takes no children.
export default function QuestionCard({
  question,
  answers,
  callback,
  userAnswer,
  questionNm,
  totalQuestions,
}: Props) {
  //duda
  return (<div>
      <p> Question :  {questionNm} / {totalQuestions} </p>
      <p dangerouslySetInnerHTML={{ __html: question }} />
      <div>
          {answers.map(function answer(){
              return(  <div>
                <button disabled={userAnswer} onClick={callback}>
                    <span dangerouslySetInnerHTML={{ __html: answer }}/>
                </button>
            </div>);
          } )}
      </div>

  </div>
    
        );
}

(错误行)

我试图删除 {{ **__html**: answer }} 留下它:{{ answer }} 但它不起作用。

【问题讨论】:

  • 提示:您的QuestionCard 定义中有一个参数answer 一个名为answer 的本地函数。也许重命名第二个(或根本不命名)。
  • 为什么您的问题是{{ **__html**: answer }},但在您的代码中,您使用的是&lt;p dangerouslySetInnerHTML={{ __html: question }} /&gt;

标签: reactjs typescript function react-props dangerouslysetinnerhtml


【解决方案1】:

这是因为,您正在为 __html 使用函数名称(React 中的一个元素):

answers.map(function answer(){
 //    __html: answer ^^

改用箭头函数:

answers.map(answer => {
  // __html: answer // now it works.

或者,如果你想继续使用函数语句,那么你可以传递一个参数并使用:

answers.map(function answer(ans){
  // __html: ans

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-22
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多