[英]I'm trying to make a collapse/accordion in React. But the problem is, it is not triggering the specific content that i want to toggle
我正在嘗試在 React 中制作折疊/手風琴。 但問題是,它不會觸發我想要切換的特定內容,即當我點擊標題時,所有段落標簽都達到了最大高度。 我知道這段代碼沒有錯誤,但我也不知道如何觸發特定的段落標簽。
這是我的反應代碼:
import React, {useState} from 'react'
import style from './stylecss.module.css'
import AnimateHeight from 'react-animate-height'
import cx from 'classname'
import globalStyles from '../Assets/global-styles/bootstrap.module.css'
function Collapse() {
const item = [
{
heading : "HEADING 1",
para : "DATA 1"
},
{
heading : "HEADING 2",
para : "DATA 2"
}
]
const [state, setState] = useState("0")
function displayPara (){
console.log(itemPlace)
if(state==0)
setState("auto")
else
setState(0)
}
const itemPlace = item.map(({heading, para}) => {
return (
<div>
<h5 onClick={ e => displayPara()}>
{heading}
</h5>
<AnimateHeight duration={ 500 } height={ `${state}` }>
<p>{para}</p>
</AnimateHeight>
</div>
)
})
return (
<div className={style.AboutPage}>
{itemPlace}
</div>
)
}
export default Collapse
這是 CSS 代碼
.AboutPage {
margin-top : 40px;
padding : 30px 6% 10px 6%;
background-color: rgb(250, 250, 250);
display: flex;
flex-direction: column;
text-align: left;
}
.paraDiv {
color : red !important;
width: 100%;
height : 100%;
background-color: chartreuse;
transition: max-height 0.5s;
}
.paraDiv.is-active {
height: 300px;
}
我不希望使用內置或預定義的折疊組件。
你可以在本地做。
<details> <summary>Epcot Center</summary> <p>Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.</p> </details>
首先祝你好運!
您的代碼所說的是:當用戶單擊其中一項(特別是 h5 標簽)時,將高度設置為自動。 你給每個項目這個高度,不區分它是否應該打開。
因此,您要做的是將您在“狀態”屬性中更改的高度僅應用於用戶單擊的項目。
我添加了幾行代碼來實現它。
activeItem
,它指示哪些是活動項(用戶單擊的項)。activeItem
。在這里你可以看到它。
import React, {useState} from 'react' import style from './stylecss.module.css' import AnimateHeight from 'react-animate-height' import cx from 'classname' import globalStyles from '../Assets/globalstyles/bootstrap.module.css' function Collapse() { const item = [ { heading: "HEADING 1", para: "DATA 1" }, { heading: "HEADING 2", para: "DATA 2" } ] const [state, setState] = useState("0") const [activeItem, setActiveItem] = useState(null) function displayPara (index){ console.log(itemPlace) setActiveItem(index) if(state==0) setState("auto") else setState(0) } const itemPlace = item.map(({heading, para}, index) => { return ( <div> <h5 onClick={ e => displayPara(index)}> {heading} </h5> <AnimateHeight duration={ 500 } height={ `${activeItem === index? state: 0}` }> <p>{para}</p> </AnimateHeight> </div> ) }) return ( <div className={style.AboutPage}> {itemPlace} </div> ) } export default Collapse
正如上面的評論之一所說,您也可以在不持有任何 state 的情況下,使用詳細信息和摘要 HTML 標簽來實現它。 您還可以使用 CSS 將其設置為與您的設計完全相同。
<details> <summary>Heading 1</summary> <p>Heading 1 Content</p> </details>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.