我有一種情況,一旦我點擊一個影像,我希望它有一個邊框。如果我再次單擊它,我希望洗掉該邊框。但是,如果單擊另一個影像,我也希望洗掉(或“移動”)該邊框!
我想有幾種方法可以解決這個問題 - 這兩種方法我都不知道如何實作:
- 清除所有影像的邊界
- 跟蹤以前的狀態并以這種方式獲取元素
我使用的是從曾祖父母傳下來的狀態,所以不確定我可以發布所有腳本 - 我試著把它保存在片段中。
我的影像:使用“下一個/影像”
return(
<div key={attr} id={attrprops.attrChoice ':' attr}>
<Image
src={imgSourceUrl}
alt={attrprops.alt}
width={attrprops.w}
height={attrprops.h}
onClick={()=>{ attrprops.setButtonClick(!attrprops.buttonClick);
attrprops.setBorder(attrprops.selectedAttr==attr ? false : true);
attrprops.setSelectedAttr(attr);
}}
/>
<br></br>
<div className='flex justify-center align-center'>{attr}</div>
</div>
);
我的狀態變化:
useEffect(()=>{
if (border&&buttonClick){
document.getElementById(`body_type:${selectedAttr}`).className = 'border-2 border-blue-500';
publishprops.setAttrNumber(4);
}
else if (!border&&buttonClick){
document.getElementById(`body_type:${selectedAttr}`).className = 'border:none';
publishprops.setAttrNumber(2);
}
},[border])
按照目前的方式,它只為選定的影像添加邊框。真的不知道該走哪條路……
uj5u.com熱心網友回復:
為了有效地使用 React,您需要稍微改變對狀態的看法。你的模板應該很容易閱讀,應該很清楚意圖是什么。
看起來你的例子很簡單。它要么突出顯示了一些影像,要么沒有。
考慮這個簡化的例子:
import React, { useState } from 'react';
const images = [
'1.png',
'2.png',
'3.png',
'4.png',
'5.png',
];
const MyComponent = () => {
const [selectedImage, setSelectedImage] = useState(null);
return (
<ul>
{images.map(src => (
<img
key={src}
className={`
my-image
${selectedImage === src ? 'active' : ''}
`}
onClick={() => setSelectedImage(
selectedImage => (
selectedImage !== src
? src
: null
)
)}
/>
))}
</ul>
);
};
當selectedImage是null它意味著沒有影像已被點擊。在單擊時,我們要么將其設定為單擊的影像,要么將其設定回null是否單擊了相同的影像。然后您將邊框應用于具有active類的影像。簡化的 CSS:
.my-image {
border: 5px solid transparent;
}
.my-image.active {
border-color: red;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/323467.html
標籤:javascript 反应 下一个.js
上一篇:CreateReactApp卸載組件并在有任何更改時重新安裝它
下一篇:將資料傳遞給組件時出現未定義錯誤
