0
我試圖做一個簡單的下拉菜單,但我有一些onClick事件在子組件中的列表項上,'handleClick'函數是假設觸發點擊時一個列表項,但是當頁面加載時(因爲這裏有兩個列表),該函數被觸發兩次,並且當我再次點擊列表時,它會再次觸發兩次,我相信這是一個簡單的問題,但我通過了幾個小時但我真的不明白這裏發生了什麼,希望有人能幫助我,謝謝!當在React應用程序中初始化時觸發按鈕onClick
這裏是我的代碼:
import React from 'react';
import Dropdown from './../elements/dropdown.js!jsx';
export class TestPage extends React.Component {
constructor() {
super();
this.noteLIst = [
{name: 'note', label: 'Note global'},
{name: 'digitalCulture', label: 'Digital Culture'}
];
}
handleItemClick(company) {
console.log(company);
}
render() {
return (
<div className="widget">
<Dropdown list={this.noteLIst} selected={this.noteLIst[0]} whenItemClicked={this.handleItemClick} />
</div>
);
}
}
Dropdown.js
import React from 'react';
export class Dropdown extends React.Component {
constructor() {
super();
this.state = {
listVisible: false
};
}
showMenu() {
this.setState({
listVisible: true
});
document.addEventListener("click", this.hide);
}
hide() {
this.setState({
listVisible: false
});
document.removeEventListener("click", this.hide);
}
handleClick(item) {
console.log(item); // Here will log 2 items
this.props.whenItemClicked(item);
}
render() {
let listItems = _.map(this.props.list, (list, index) => {
return (
<li key={index} className={list} onClick={this.handleClick(list)}>{list.name}</li>
);
});
return (
<div className = {"dropdown-container" + (this.state.listVisible ? " show" : "")}>
<div className = {"dropdown-display" + (this.state.listVisible ? " clicked" : "")} onClick = {this.show}>
<span>
<img className="icon-arrow-bottom" src="build/image/arrow_bottom_black.png" />
</span>
<span>
{this.props.selected.name}
</span>
</div>
<ul className="dropdown-list" >
{listItems}
</ul>
</div>
);
}
}