为什么 Material-UI Appbar onLeftIconButtonTouchTap 不起作用?

IT技术 javascript reactjs redux material-ui
2021-04-30 23:25:20

我正在研究 React-Redux、Material-UI。
现在,我正在尝试创建示例应用程序,但不起作用。
我不知道如何改进我的代码。
我想打开 Drawer ,当 Material-UI AppBar onLeftIconButtonTouchTap 被点击时。
我想我不能将我的 Action 绑定到 Component。
当以下代码运行时,不会触发 onLeftIconButtonTouchTap 事件。
当我将 openDrawer 更改为 openDrawer() 时,在 Chrome 开发工具上发现了 JS 错误“openDrawer 不是函数”。

Header.jsx 作为组件

import React, { PropTypes } from 'react';
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';

const Header = ({
  openDrawer,
  open
}) => (
  <div>
    <AppBar
      title='sample'
      onLeftIconButtonTouchTap = {() => openDrawer}
    />
    <Drawer 
      docked={false}
      open={open}
    />
  </div>
)

Header.PropTypes = {
  openDrawer: PropTypes.func.isRequired,
  open: PropTypes.bool.isRequired
}

export default Header;

HeaderContainer.jsx 作为容器

import React from 'react';
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux';

import { header } from '../actions'
import Header from '../components/Header';

const mapStateToProps = (state) => ({open});
const mapDispatchToProps = (dispatch) => (
  {openDrawer: bindActionCreators(header, dispatch)}
);

const HeaderContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(Header);

export default HeaderContainer;

App.jsx 作为 RootComponent

import React, { Component, PropTypes } from 'react';

import Header from '../components/Header';

import injectTapEventPlugin from "react-tap-event-plugin";

import baseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import getMuiTheme from 'material-ui/styles/getMuiTheme';

injectTapEventPlugin();

class App extends Component {
  constructor(props) {
    super(props);
  }

 getChildContext() {
      return { muiTheme: getMuiTheme(baseTheme) };
  }

  render() {
    return (
      <div>
        <Header />
        {this.props.children}
      </div>
    );
  }
};

App.childContextTypes = {
    muiTheme: React.PropTypes.object.isRequired,
};

export default App;

提前致谢。

1个回答

您没有正确绑定函数。您需要将代码更新为

<AppBar
  title='sample'
  onLeftIconButtonTouchTap = { openDrawer.bind(this) }
/>

更多关于.bind()这里的方法:使用 JavaScript 'bind' 方法