如何在React和Material-ui中设置.js文件的状态?

时间:2017-10-22 22:16:17

标签: reactjs material-ui

我也是ReactMaterial-UI的新人。我有这个App.js文件:

import React, {Component} from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import IconButton from 'material-ui/IconButton';
import NavigationMenu from 'material-ui/svg-icons/navigation/menu';
import DrawerMenu from './DrawerMenu';

const AppBarIcon = () => (
  <AppBar
    title="Title"
    iconElementLeft={<IconButton onClick={???}>
                         <NavigationMenu />
                     </IconButton>}
  />
);

class App extends Component {
    render() {
        return (
            <div className="App">
                <MuiThemeProvider>
                    <div>
                        <DrawerMenu />
                        <AppBarIcon />
                    </div>
                </MuiThemeProvider>
             </div>
        );
    }
}

export default App;

...这是DrawerMenu.js文件:

import React from 'react';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';

export default class DrawerSimpleExample extends React.Component {

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

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

  render() {
    return (
      <div>
        <Drawer open={this.state.open}>
          <MenuItem>Menu Item</MenuItem>
          <MenuItem>Menu Item 2</MenuItem>
        </Drawer>
      </div>
    );
  }
}

有没有办法在App.js文件中设置IconButton的onClick值来设置DrawerMenu的状态open:true?例如:

<IconButton onClick={ DrawerMenu.setState({open:true}) }>

...或类似的东西?

1 个答案:

答案 0 :(得分:2)

您可以使用道具来实现所需的行为。

示例

const AppBarIcon = (props) => (
  <AppBar
    title="Title"
    iconElementLeft={<IconButton onClick={props.onIconClick}>
                         <NavigationMenu />
                     </IconButton>}
  />
);

class App extends Component {
    constructor(props) {
      super(props);
      this.state = { isOpen: false };
    }

    onIconClick = () => {
      this.setState((prevState) => ({ isOpen: !prevState.isOpen }));
    }
    render() {
        return (
            <div className="App">
                <MuiThemeProvider>
                    <div>
                        <DrawerMenu isOpen={this.state.isOpen} />
                        <AppBarIcon onIconClick={this.onIconClick} />
                    </div>
                </MuiThemeProvider>
             </div>
        );
    }
}
export default class DrawerSimpleExample extends React.Component {

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

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


  render() {
    return (
      <div>
        <Drawer open={this.props.isOpen}>
          <MenuItem>Menu Item</MenuItem>
          <MenuItem>Menu Item 2</MenuItem>
        </Drawer>
      </div>
    );
  }
}