我试图制作一个简单的下拉菜单,但是我在列表项上的onClick事件上遇到了一些问题,这些列表项在子组件中,' handleClick'我想在单击列表项时触发函数,但是当页面加载时该函数被触发两次(因为这里有两个列表),当我再次点击列表时,它会再次触发两次,我确定这是一个简单的问题,但我通过了几个小时,但我真的不明白这里发生了什么,希望有人可以帮助我,谢谢!
这是我的代码:
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>
);
}
}
答案 0 :(得分:3)
当您使用onClick事件并且想要将参数传递给处理程序方法时,您必须使用函数bind
。因此,仅当您单击列表项时才会触发处理程序。
onClick={this.handleClick.bind(this, list)}
这将是你的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); // it will be log 1 item when you click
this.props.whenItemClicked(item);
}
render() {
let listItems = _.map(this.props.list, (list, index) => {
return (
<li key={index} className={list} onClick={this.handleClick.bind(this, 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>
);
}
}