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

IT技术 reactjs material-ui
2021-04-28 13:36:23

我是新的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个回答

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

例子

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>
    );
  }
}