我正在將一組物件從外部 js 檔案傳遞??給主要組件以進行渲染:
const students = filteredStudents.map(i =>
<div key={i.id} className='d-flex border-bottom'>
<img src={i.pic} className='align-self-center border rounded-circle mx-4' />
<div className='my-3'>
<h2 className='fw-bold'>{i.firstName.toUpperCase()} {i.lastName.toUpperCase()}</h2>
<div className='text-secondary ms-4'>
<p className='mb-0'>Email: {i.email}</p>
<p className='mb-0'>Company: {i.company}</p>
<p className='mb-0'>Skill: {i.skill}</p>
<p className='mb-0'>Average: {getAverageScore(i.grades)}%</p>
<div className='mt-2 d-none'>
{getGrades(i.grades)}
</div>
</div>
</div>
// Here is a button
</div>
);
return students;
主要組件渲染:
const items = renderStudents(this.state.query, this.state.students);
return (
<div id='students-card' className='overflow-auto border shadow-lg'>
<input className='w-100' placeholder='Search by name' onChange={this.handleChange} value={this.state.query} />
{items} // Array of objects being rendered here
</div>
);
想象有一個按鈕而不是評論,當用戶點擊它時,d-none應該打開和關閉。我完全陷入了困境。我應該將每個學生物件呈現為具有狀態而不是我的方式的單個組件嗎?
uj5u.com熱心網友回復:
您可以分配一個 id 并將其存盤到本地狀態,將其用作當前所選專案的識別符號,您可以執行您的邏輯。
檢查以下示例
const [selectedGrade, setGrade] = React.useState(null)
const [show, setShow] = React.useState(true)
const handleHideShowGrade = (id) => {
setGrade(id)
setShow(!show)
}
const students = filteredStudents.map((i, idx) =>
<div key={i.id} className='d-flex border-bottom'>
<img src={i.pic} className='align-self-center border rounded-circle mx-4' />
<div className='my-3'>
<h2 className='fw-bold'>{i.firstName.toUpperCase()} {i.lastName.toUpperCase()}</h2>
<div className='text-secondary ms-4'>
<p className='mb-0'>Email: {i.email}</p>
<p className='mb-0'>Company: {i.company}</p>
<p className='mb-0'>Skill: {i.skill}</p>
<p className='mb-0'>Average: {getAverageScore(i.grades)}%</p>
<div className={`mt-2 ${selectedGrade === idx && show ? '' : 'd-none'}`}>
{getGrades(i.grades)}
</div>
</div>
</div>
// Here is a button
<button onclick={() => handleHideShowGrade(idx)}
</div>
);
return students;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487843.html
標籤:javascript 反应
