![](/img/trans.png)
[英]e.target is accessible, but e.target.value is not in React component
[英]React dropdown only show value if clicked on specific data using e.target?
所以我正在尝试制作这个手风琴,现在它通过我的数据进行映射,并且当我点击我的h1
时基本上显示所有下拉值,但我只希望它显示我点击的特定h1
的下拉列表而不显示整体价值
const Accordion = () => {
const [clicked, setClicked] = useState(false);
const toggle = e => {
if (e.target) {
setClicked(!clicked);
}
console.log(e.target);
};
return (
<div>
{Data.map((item, index) => {
return (
<div key={index}>
<h1 onClick={e => toggle(e)}>{item.question}</h1>
{clicked ? (
<div>
<p>{item.answer}</p>
</div>
) : null}
</div>
);
})}
</div>
);
};
我的开关 function 显示了我点击的 h1 的正确 e.target 值,但我不知道如何在我点击它时只显示该h1
值而不是显示所有h1's
值
这是我的数据文件
export const Data = [
{
question: 'What 1?',
answer: 'answer 1'
},
{
question: 'What 2',
answer: 'answer 2'
},
{
question: 'What 3?',
answer: 'answer 3'
}
];
我如何重构我的代码以仅显示问题 1 和答案 1,而不是在单击时显示所有问题和答案?
我的建议是使用它自己的 state 的单独组件,并将其用于每个手风琴项目。
const AccordionItem = (props) => {
const [clicked, setClicked] = useState(false);
return (
<div>
<h1 onClick={() => setClicked(! clicked)}>{props.question}</h1>
{clicked && (
<div>
<p>{item.answer}</p>
</div>
)}
</div>
);
};
const Accordion = () => {
return (
<div>
{Data.map((item, index) => {
return (
<AccordionItem
key={index}
question={item.question}
answer={item.answer}
/>
);
})}
</div>
);
};
您必须将点击的问题放在 state 中,而不仅仅是是否点击了某些内容。 例如https://codesandbox.io/s/summer-night-4uulw?file=/src/App.js
const Data = [
{
question: 'What 1?',
answer: 'answer 1',
},
{
question: 'What 2',
answer: 'answer 2',
},
{
question: 'What 3?',
answer: 'answer 3',
},
];
const Accordion = () => {
const [activeQn, setActiveQn] = useState(null);
const toggle = ( index ) => {
// If the clicked qn is already active, then collapse it
if ( activeQn === index ) {
return setActiveQn(null)
}
// Otherwise show the answer to the clicked qn
setActiveQn(index)
};
return (
<div>
{Data.map((item, index) => {
return (
<div key={index}>
<h1 onClick={() => toggle(index)}>{item.question}</h1>
{activeQn === index ? (
<div>
<p>{item.answer}</p>
</div>
) : null}
</div>
);
})}
</div>
);
};
这样,只有点击的答案才会显示,如果用户希望折叠答案,也可以这样做。
您需要跟踪单击了哪个 div。 您可以像这样在数据中分配id
:
const Data = [
{
question: "What 1?",
answer: "answer 1",
id: 0
},
{
question: "What 2",
answer: "answer 2",
id: 1
},
{
question: "What 3?",
answer: "answer 3",
id: 2
}
];
然后在toggle
方法上发送此 id 并检查 id 是否等于所选的一个或不这样:
const toggle = (e, id) => {
if (e.target) {
setSelected(id === selected ? null : id); //selected and id are same it means close the toggle
}
console.log(e.target);
};
内部渲染检查如下:
{selected === item.id ? (
<div>
<p>{item.answer}</p>
</div>
) : null}
这是完整的演示和代码: https://codesandbox.io/s/toggle-accordian-eplpw
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.