如果单击页面上的任何位置,则重置回样式颜色



我有以下带有onclick事件的元素,如果用户点击,它将把点击的段落涂成红色:-

<p
onClick={(e)=> e.currentTarget.style.color = "red"}
>
Click here 
</p>
<p
onClick={(e)=> e.currentTarget.style.color = "red"}
>
Another Paragraph 
</p>
<p
onClick={(e)=> e.currentTarget.style.color = "red"}
>
Another Paragraph 
</p>

如果用户单击页面上的其他位置或单击另一段,如何将颜色重置为原始黑色。

您可以为<body>元素编写事件处理程序。如果未取消,则单击事件"气泡"直至<body>。你应该取消你的活动,这样它们就不会"冒泡"到<body>:

<p onClick={(e)=> e.currentTarget.style.color = "red"; e.stopPropagation();}>
Click here 
</p>

现在只需设置所有<p>元素的颜色:

<body onClick = {() => e.target.nodeName == "DIV" && (e.target.style.color = "black");}>

您真的不应该直接从React应用程序修改DOM。改为使用状态:

function Paragraph (props) {
const [selected, setSelected] = React.useState();
const style = selected ? { color: red } : undefined;
return (
<p {...props} style={style} />
)
}

若要在用户单击其他位置时重置它,可以在document.body处于选定状态时向其添加事件侦听器。类似这样的东西:

function Paragraph (props) {
const [selected, setSelected] = React.useState();
const style = selected ? { color: red } : undefined;
React.useEffect(() => {
if (selected) {
// you'd probably want to check to see if the click target
// is the current element; omitted here for simplicity
const onClick = () => setSelected(false);
document.body.addEventListener('click', onClick);
// remove the listener on unmount or when selected state changes
return () => document.body.removeEventListener('click', onClick);
}
}, [selected])
return (
<p {...props} style={style} />
)
}

更好的是,使用className而不是内联样式:

<p {...props} className={selected ? 'selected' : ''} />
.selected { color: red; }

您可以使用其他东西,然后再使用类。还要记住,通过这种方式,您可以在页面上的所有元素上单击事件,所以如果稍后需要,只需展开此。。。此外,可以通过多种方式重新编写以满足需求。

const click = document.querySelectorAll(".click");
[...document.querySelectorAll('body')].forEach(el => {
el.addEventListener('click', event => {
if (event.target.className.includes("click") === true) {
click.forEach(p => {
p.style.color = "black";
})
event.target.style.color = "red";
} else {
click.forEach(p => {
p.style.color = "black";
})
}
})
})
div {
width: 100% height:100%
}
<div>test div
<p class="click"> dont Click here
</p>
test div1
</div>
<p class="click"> dont Click here
</p>
<div>test div2
<p class="click"> dont Click here
</p>
</div>

最新更新