我正在尝试在Mouse Enter上添加类,并从Mouse Out上删除类。为此,我正在使用状态,我已经在组件类中声明了状态,但是无法在组件中设置
我的代码
class MegaMenu extends React.Component {
public state = { addClass: false }
public render() {
return (
<div className={styles.MegaMenu}>
<div className={styles["menu-container"]}>
<div className={styles.menu}>
<MenuList Options={menus} />
</div>
</div>
</div>
)
}
}
const MenuList = (props: IMenuListProps) => {
const { width, height } = WidthAndHeight();
const handleOnMouseEnter = () => {
if (width > 943) {
console.log('Mouse Enter')
}
}
const handleOnMouseOut = () => {
if (width > 943) {
console.log('Mouse Out')
}
}
return (
<ul onMouseEnter={handleOnMouseEnter}>
{
props.Options.map((Option: IMenu, index: number) => (
<li key={index} className={(Option.subitem && Option.subitem.length > 0) ? styles["menu-dropdown-icon"] : styles["normal-sub"]} onMouseEnter={handleOnMouseEnter} onMouseOut={handleOnMouseOut}>
<a href={Option.link}>{Option.name}</a>
{/* Base Case */}
{
(Option.subitem && Option.subitem.length > 0) &&
<MenuList Options={Option.subitem} />
}
</li>
))
}
</ul>
)
}
export default MegaMenu
我做错了!!
答案 0 :(得分:0)
您的代码已修改(我不确定您要在哪里添加/删除类):
class MegaMenu extends React.Component {
public state = { addClass: false }
public render() {
return (
<div className={styles.MegaMenu}>
<div className={styles["menu-container"]}>
<div className={styles.menu}>
<MenuList Options={menus} />
</div>
</div>
</div>
)
}
}
const MenuList = (props: IMenuListProps) => {
private state = { className: '' };
const { width, height } = WidthAndHeight();
const handleOnMouseEnter = () => {
if (width > 943) {
setState({ className: 'some-class' });
}
}
const handleOnMouseOut = () => {
if (width > 943) {
setState({ className: '' });
}
}
return (
<ul onMouseEnter={handleOnMouseEnter}> className={{this.state.className}}
{
props.Options.map((Option: IMenu, index: number) => (
<li key={index} className={(Option.subitem && Option.subitem.length > 0) ? styles["menu-dropdown-icon"] : styles["normal-sub"]} onMouseEnter={handleOnMouseEnter} onMouseOut={handleOnMouseOut}>
<a href={Option.link}>{Option.name}</a>
{/* Base Case */}
{
(Option.subitem && Option.subitem.length > 0) &&
<MenuList Options={Option.subitem} />
}
</li>
))
}
</ul>
)
}
export default MegaMenu