我是 React.js 的初学者,我正在使用 TypeScript。
我想创建一个在单击时会复制自身的元素,我该怎么做? 这是当前的代码:
import React from "react";
interface Props {
emoji: string;
text: string;
}
const Item = ({ emoji, text }: Props) => {
const HandleClick = () => {};
return (
<>
<div className="item" onClick={HandleClick}>
<span className="emoji">{emoji}</span>
<span className="text">{text}</span>
</div>
</>
);
};
export default Item;
尝试在网上搜索,尚未成功
您可以使用此代码。当您单击该项目时,它会克隆自身。
import React, { useState } from "react";
interface Props {
emoji: string;
text: string;
}
const Item = ({ emoji, text }: Props) => {
// Stores the number of clicks and clones
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1); // Track the number of clicks and clones
};
return (
<>
{new Array(count + 1).fill(null).map((_, index) => (
<div key={index} className="item" onClick={handleClick}>
<span className="emoji">{emoji}</span>
<span className="text">{text}</span>
</div>
))}
</>
);
};
export default Item;