英文:
How to toggle/display content individually in ReactJS
问题
我的问题是如何在单击时单独切换/显示"一些文本"内容?我可以为每个div使用不同的函数和状态,它可以工作,但我知道这不是正确的方法。你能帮助我吗?谢谢
这是我的代码:
function App() {
const [loaded, setLoaded] = useState(true);
const [show, setShow] = useState(false);
const handleShow = () => {
setShow(!show);
};
return (
<div className={styles.App}>
{loaded && (
<div className={styles.cards_container}>
<div className={styles.card_container} onClick={handleShow}>
<h3>Title</h3>
{show && (
<div>
<p>一些文本</p>
</div>
)}
</div>
<div className={styles.card_container} onClick={handleShow}>
<h3>Title</h3>
{show && (
<div>
<p>一些文本</p>
</div>
)}
</div>
<div className={styles.card_container} onClick={handleShow}>
<h3>Title</h3>
{show && (
<div>
<p>一些文本</p>
</div>
)}
</div>
</div>
)}
</div>
);
}
希望这有帮助。
英文:
my question is how can I toggle/display the "Some text" content on onClick individually?.
I can use different function and state for every div an it is working but I know this is not the correct way to do it .
Can you help me with this guys? Thanks
This is my code
function App() {
const [loaded, setLoaded] = useState(true);
const [show, setShow] = useState(false);
const handleShow = () => {
setShow(!show);
};
return (
<div className={styles.App}>
{loaded && (
<div className={styles.cards_container}>
<div className={styles.card_container} onClick={handleShow}>
<h3>Title</h3>
{show && (
<div>
<p>Some text</p>
</div>
)}
</div>
<div className={styles.card_container} onClick={handleShow}>
<h3>Title</h3>
{show && (
<div>
<p>Some text</p>
</div>
)}
</div>
<div className={styles.card_container} onClick={handleShow}>
<h3>Title</h3>
{show && (
<div>
<p>Some text</p>
</div>
)}
</div>
</div>
)}
</div>
);
}
答案1
得分: 0
你可以为你的卡片创建一个自定义组件来处理每个卡片的状态:
function Card() {
const [show, setShow] = useState(false);
const handleShow = () => {
setShow((state) => !state);
};
return (
<div className={styles.card_container} onClick={handleShow}>
<h3>Title</h3>
{show && (
<div>
<p>Some text</p>
</div>
)}
</div>
);
}
然后在你的应用中使用它:
function App() {
const [loaded, setLoaded] = useState(true);
return (
<div className={styles.App}>
{loaded && (
<div className={styles.cards_container}>
<Card />
<Card />
<Card />
</div>
)}
</div>
);
}
英文:
You could create a custom component for your card that handles the state for each card:
function Card() {
const [show, setShow] = useState(false);
const handleShow = () => {
setShow(state => !state);
};
return <div className={styles.card_container} onClick={handleShow}>
<h3>Title</h3>
{show && (
<div>
<p>Some text</p>
</div>
)}
</div>
}
And use it in your app:
function App() {
const [loaded, setLoaded] = useState(true);
return (
<div className={styles.App}>
{loaded && (
<div className={styles.cards_container}>
<Card />
<Card />
<Card />
</div>
)}
</div>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论