【发布时间】:2019-08-16 07:46:19
【问题描述】:
我正在尝试创建一个可以呈现“peg”的反应组件:
或“nopeg”(它只是一个没有钉子的空白区域)。这仅通过更改 Peg 组件的类来完成。我还有另一个目的。如果单击 peg 并且其类是“nopeg”,那么我想立即将 Peg 更改为“peg”类,然后等待 1 秒钟,然后将其更改回“nopeg”。这是使用 React.js 完成的:
class Peg extends React.Component {
constructor(props) {
super(props);
this.handleDrop = this.handleDrop.bind(this);
}
handleDrop(event) {
if (event.target.className == 'nopeg') {
event.target.className = 'peg'
setTimeout((e) => {
e.target.className = 'nopeg'
}, 1000, event)
}
}
render() {
const classdef = this.props.class;
const iddef = this.props.id;
return <div id={iddef} class={classdef} onClick={this.handleDrop}></div>
}
}
如您所见,setTimeout 函数通过输入事件对象,等待 1 秒,然后更改类名来处理等待。由于某种原因,这不起作用,我只能将 peg 更改为“nopeg”。
【问题讨论】:
-
应该
event.target.className = 'nopeg'. Not e -
不,我将事件对象作为第三个参数传递给 setTimout 函数。请参阅 setTimeout 文档:developer.mozilla.org/en-US/docs/Web/API/…@ThanhNgo
-
@Herohtar 我正在使用 codepen.io,渲染时没有错误。
e.target.className = 'nopeg'只是不执行 -
可以分享一下codepen.io
-
有点复杂。在 top 中输入
3,在 side 中输入2,它将渲染钉子。单击钉子之间的空格以启动 handleClick 功能:codepen.io/lectrician1/pen/BbPadN
标签: javascript html reactjs dom