【发布时间】: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) => boolean' is not assignable to parameter of type 'SetStateAction<showContent>'.<br/>Type '(s: showContent) => boolean' is not assignable to type '(prevState: showContent) => 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 调用以匹配您的界面。
() => setShowMore((s) => ({state: !s.state}))
标签: javascript html reactjs typescript