我使用this包装来检测菜单外的点击以打开/关闭它。它有点工作,但是当我点击按钮打开时它会出现问题,OnClickOutside包装器关闭它,然后按钮再次切换它(只需点击一下):
我想知道如何解决这个问题,这就是我的组件的外观:
import React from 'react';
import List from './list';
export default class ItemHeader extends React.Component {
constructor(props){
super(props);
this.state = {
showList: false
};
}
render() {
<div>
<button onClick = {this.toggleList.bind(this)}></button>
{this.renderList()}
</div>
}
renderList() {
let data = [1, 2, 3, 4, 5];
if (this.state.showList) {
return (
<List
data = {data}
toggleList = {this.toggleList.bind(this)}
/>
);
};
}
toggleList() {
if(!this.state.showList) {
this.setState({ showList: true });
} else this.setState({ showList: false });
}
}
这里是列表(用作菜单)组件:
import React from 'react';
import OnClickOutside from 'react-onclickoutside';
export default class List extends React.Component {
constructor(props) {
super(props);
this.state = {
data: this.props.data
};
}
render() {
return (
<ul>
{this.state.data.map(
(listItem, i) => <li key = {i}>{listItem}</li>
)}
</ul>
);
}
// Handle click away here:
handleClickOutside() {
this.props.toggleList();
}
}
export default OnClickOutside(List);