【问题标题】:Convert dynamic class by state value from react to typescript按状态值将动态类从反应转换为打字稿
【发布时间】:2021-12-14 04:51:08
【问题描述】:

我需要使用这个 react 函数,但是在 typescript 中

const ListItem = ({ text }) => {
    let [showMore, setShowMore] = useState(false);

    return (
        <div className="item">
            <div>
                <div className={`text ${showMore ? "active" : ""}`}>{text}</div>
            </div>
            <button onClick={() => setShowMore((s) => !s)}>Show more</button>
        </div>
    );
};

我尝试过类似的方法,但出现了一些错误

<html>TS2345: Argument of type '(s: showContent) =&gt; boolean' is not assignable to parameter of type 'SetStateAction&lt;showContent&gt;'.<br/>Type '(s: showContent) =&gt; boolean' is not assignable to type '(prevState: showContent) =&gt; showContent'.<br/>Type 'boolean' is not assignable to type 'showContent'.
interface showContent {
  state: boolean;
}

let [showMore, setShowMore] = React.useState<showContent>({ state: false });

    return (
        <div className="item">
            <div>
                <div className={`text ${showMore ? "active" : ""}`}>{text}</div>
            </div>
            <button onClick={() => setShowMore((s) => !s)}>Show more</button>
        </div>
    );

【问题讨论】:

  • 抱歉没有读到你的第二个代码块。您没有更新 setState 调用以匹配您的界面。 () =&gt; setShowMore((s) =&gt; ({state: !s.state}))

标签: javascript html reactjs typescript


【解决方案1】:

转换成打字稿

如果您打算将第一个块转换为打字稿,那么您不需要 showContent 接口,因为您只提供一个布尔值。

import React, { ReactNode, useState } from "react";

interface Props {
  text: ReactNode;
}

const ListItem = ({ text }: Props) => {
    let [showMore, setShowMore] = useState(false);

    return (
        <div className="item">
            <div>
                <div className={`text ${showMore ? "active" : ""}`}>{text}</div>
            </div>
            <button onClick={() => setShowMore((s) => !s)}>Show more</button>
        </div>
    );
};

this Typescript Playground

关于错误

你得到的错误:

“(s: showContent) => boolean”类型的参数不可分配给“SetStateAction”类型的参数。
类型 '(s: showContent) => boolean' 不可分配给类型 '(prevState: showContent) => showContent'。
类型 'boolean' 不可分配给类型 'showContent'。(2345)

试图告诉您,您不能将boolean(意思是truefalse)分配给带有签名{ state: boolean; } 的对象。这就是为什么@pilchard 建议创建一个对象来匹配您的界面 ({ state: !s.state })。

但是正如上面的代码所示,我认为你根本不需要这个对象,这似乎是一个打字错误。

【讨论】:

    猜你喜欢
    • 2017-08-10
    • 2021-08-30
    • 1970-01-01
    • 2020-06-22
    • 2020-03-09
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    相关资源
    最近更新 更多