我的问题是尝试从渲染函数内部调用selectModal。我认为问题是我需要在构造函数中绑定selectModal函数,但这无济于事。我仍然得到相同的错误:
FolderIcon.js:37 Uncaught TypeError: 無法在 singleClick (FolderIcon.js:37) 時讀到未定義的產物業 'selectModal'
当我像这样在HTML标签中使用箭头函数时,它可以工作,onClick={ () => this.selectModal('Modal A') },但我尝试仅在双击图像时才打开弹出窗口
代码如下:
class FolderIcon extends Component{
constructor(props){
super(props);
this.state = {
modal: false,
modalInfo: ""
}
this.selectModal = this.selectModal.bind(this);
}
selectModal = (info) => {
this.setState({
modal: !this.state.modal,
modalInfo: info
})
}
render() {
let clicks = [];
let timeout;
function singleClick(event) {
this.selectModal('Modal A');
alert("single click");
}
function doubleClick(event) {
alert('double clicked')
}
function clickHandler(event) {
event.persist()
event.preventDefault();
clicks.push(new Date().getTime());
window.clearTimeout(timeout);
timeout = window.setTimeout(() => {
if (clicks.length > 1 && clicks[clicks.length - 1] - clicks[clicks.length - 2] < 250) {
doubleClick(event.target);
} else {
singleClick(event.target);
}
}, 250);
}
return (
<>
<div>
<img src={foldericon} onClick={clickHandler} alt="" className="folder"/>
<p onClick={ () => this.selectModal('Modal A') }>
Open Modal A
</p>
<Modal
displayModal={this.state.modal}
modalInfo={this.state.modalInfo}
closeModal={this.selectModal}/>
</div>
</>
);
}
}
export default FolderIcon;
慕婉清6462132
拉风的咖菲猫
相关分类