如何在加载(React)上运行简单的切换功能?

时间:2018-02-20 15:40:00

标签: javascript reactjs material-ui

我试图通过在组件加载时切换侧边栏的状态(从open:false到open:true)来让我的侧边栏滑入。我这样做是为了在用户加载页面后尝试获得滑入效果。

不幸的是,就我现在这样做的方式而言,似乎状态已经改变,组件基本上立即重新渲染,从而阻止了滑入效果的发生。这是我的代码:

export default class Sidebar extends React.Component {

  constructor(props) {
    super(props);
    this.state = {open: false};
  }

  componentDidMount() {
      this.setState({open: !this.state.open})
  }

  handleToggle = () => this.setState({open: !this.state.open});

  render() {
    return (
      <div>
        <Drawer width={'25%'} open={this.state.open}>
         <AppBar title="Wealth Management" onLeftIconButtonClick={this.handleToggle}/>
          <MenuItem>Menu Item</MenuItem>
          <MenuItem>Menu Item 2</MenuItem>
        </Drawer>
      </div>
    );
  }
}

你如何让这个工作?我是否更新了错误的生命周期方法?

2 个答案:

答案 0 :(得分:1)

它被称为 CSS过渡

您可以查看此medium post或查看MDN documentation

答案 1 :(得分:0)

我们使用基于用户设置滑动打开或关闭的侧边栏,诀窍是在基础css-class&#34; sidebar&#34;上设置负边距。在这种情况下。 然后添加/删除切换类(在渲染或按钮事件上)。这就是在加载时获得smoth动画所需的全部内容

css-classes:

.sidebar {
  z-index: 1000;
  position: fixed;
  left: 200px;
  top: 0px;
  bottom: 0px;
  width: 250px;
  margin-left: -250px;
  -webkit-transition: all 0.5s ease;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  transition: all 0.5s ease;
}

.sidebarToggled {
  width: 65px;
}