首页 > 解决方案 > reactjs中Web应用程序的三点更多选项菜单的逻辑

问题描述

我是 ReactJs 的新手,我正在开发一个社交媒体网络应用程序。在这里,我有一个模板,我必须在其中实现一个三点更多选项菜单。我尝试使用 Bootstrap 菜单并对 Bootstrap 组件菜单做出反应。两者都不适合我。在不使用库的情况下实现此功能的最佳方法是什么?

我一直这样做,直到切换菜单。但是在点击时,所有菜单都会完全切换。我无法单独进行切换。

在此处输入图像描述

这是我做的一段代码:

post.jsx

class UserPost extends Component {
    state = {
      overFlowMenuActive: false
    };

    toggleOverflowMenu = () => {
      this.setState((prevState) => ({ overFlowMenuActive: 
         !prevState.overFlowMenuActive }));
    };

    closeOverflowMenu = () => {
        this.setState({ overFlowMenuActive: false });
    };

    render() {
     return (
        <React.Fragment>
            {this.props.posts.map((post, index) =>(
               <div>
                 <div tabIndex='0' onBlur={this.closeOverflowMenu}>
                     <img src={require('../../assets/images/more.svg')} alt='' onClick={this.toggleOverflowMenu}/>
                 </div>
                 <MoreBtn options={this.state.options} overFlowMenuActive={this.state.overFlowMenuActive} />
                </div>
             ))}
        </React.Fragment>
    );
}

更多Btn.jsx

<div className={`${classes['popup-more']} ${this.props.overFlowMenuActive
                    ? classes.expand
                    : classes.collapse}`}>
    {this.props.options.map((option, index) => (
        <div key={index}>
            <img src={option.url} alt='' />
            <p>{option.name}</p>
        </div>
    ))}
</div>

标签: reactjs

解决方案


您只为所有人维护一个状态UserPosts

要分别切换这些状态,应将这些状态移动到组件中。

class SinglePost extends Component {
    state = {
      overFlowMenuActive: false
    };

    toggleOverflowMenu = () => {
      this.setState((prevState) => ({ overFlowMenuActive: 
         !prevState.overFlowMenuActive }));
    };

    closeOverflowMenu = () => {
        this.setState({ overFlowMenuActive: false });
    };

    render() {
     return (
        <div>
                 <div tabIndex='0' onBlur={this.closeOverflowMenu}>
                     <img src={require('../../assets/images/more.svg')} alt='' onClick={this.toggleOverflowMenu}/>
                 </div>
                 <MoreBtn options={this.state.options} overFlowMenuActive={this.state.overFlowMenuActive} />
                </div>
    );
}
class UserPost extends Component {
    render() {
     return (
        <React.Fragment>
            {this.props.posts.map((post, index) =>(
               <SinglePost post={post} />
             ))}
        </React.Fragment>
    );
}

这样,一次只切换一个组件的按钮


推荐阅读