首先,对不起,我的英语不好。我想制作一个类别树组件,而blew是我的渲染代码。
class tree extends Component {
constructor(props) {
super(props);
this.state = {
showBig1: false,
showBig2: false,
showSmall1: false,
showSmall2: false,
current: 'fake',
fake: false
};
}
toggleBigMenu = (type, current_now) => {
this.state = {
[current_now]: false,
[type]: true,
current: type
}
}
render() {
const {showBig1, showBig2, showSmall1, showSmall2} = this.state
return (
<div>
<li className={showBig1 ? "on" : "off"} onClick={this.toggleBigMenu("showBig1", current)}>
<Link to="#">
<span>BIG MENU 1</span>
</Link>
</li>
<li className={showBig2 ? "on" : "off"} onClick={this.toggleBigMenu("showBig2", current)}>
<Link to="#">
<span>BIG MENU 2</span>
</Link>
<ul>
<li className={showSmall1 ? "on" : "off"} onClick={this.toggleBigMenu("showSmall1", current)}>
<Link to="#">
<span>SMALL MENU 1</span>
</Link>
</li>
<li className={showSmall2 ? "on" : "off"} onClick={this.toggleBigMenu("showSmall2", current)}>
<Link to="#">
<span>SMALL MENU 2</span>
</Link>
</li>
</ul>
</li>
</div>
)
}
}
,我一次只能单击一个“ li”项。 但是,当我单击BIG MENU1时,它与BIG MENU 2一起单击。 而且BIG MENU 2的状态变为true,但是我想将BIG MENU 1的状态设置为
。我不知道该怎么解决..请任何人帮助我。 谢谢。
答案 0 :(得分:0)
通过编写onClick={this.toggleBigMenu("showBig1", current)}
,您可以直接在渲染上调用this.toggleBigMenu
。您可以创建一个新函数,该事件将在事件发生时调用。
您可以将所有菜单重设为current
,而不必将每次更改菜单都传递给false
,只需将单击的菜单设置为true
即可。
由于您的菜单位于其他菜单中,因此在click事件上调用event.stopPropagation()
也是一个好主意,这样嵌套菜单就有机会被选中。
示例
const menus = {
showBig1: false,
showBig2: false,
showSmall1: false,
showSmall2: false
};
class Tree extends React.Component {
state = { ...menus };
toggleMenu = (event, type) => {
event.stopPropagation();
this.setState({
...menus,
[type]: true
});
};
render() {
const { showBig1, showBig2, showSmall1, showSmall2, current } = this.state;
return (
<div>
<li
style={{ backgroundColor: showBig1 ? "green" : "red" }}
onClick={event => this.toggleMenu(event, "showBig1")}
>
<span>BIG MENU 1</span>
</li>
<li
style={{ backgroundColor: showBig2 ? "green" : "red" }}
onClick={event => this.toggleMenu(event, "showBig2")}
>
<span>BIG MENU 2</span>
<ul>
<li
style={{ backgroundColor: showSmall1 ? "green" : "red" }}
onClick={event => this.toggleMenu(event, "showSmall1")}
>
<span>SMALL MENU 1</span>
</li>
<li
style={{ backgroundColor: showSmall2 ? "green" : "red" }}
onClick={event => this.toggleMenu(event, "showSmall2")}
>
<span>SMALL MENU 2</span>
</li>
</ul>
</li>
</div>
);
}
}
ReactDOM.render(<Tree />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>