【问题标题】:Edit component property onClick Next.js编辑组件属性 onClick Next.js
【发布时间】:2019-05-28 07:32:24
【问题描述】:

我是 Next.js 的新手,寻求您的支持来解释如何为组件的属性传递新值。我使用 Material-UI 库进行样式设置。

在尝试更改抽屉组件的 open 属性时,它总是向我显示 [TypeError] open 是只读的。

const drawer = (
  <SwipeableDrawer open={drawerOpened}>
    <div tabIndex={0} role="button">
      {sideList}
    </div>
  </SwipeableDrawer>
);

const handleClick = e => {
  drawerOpened = !drawerOpened;
  drawer.props.open = drawerOpened;
  e.preventDefault();
};

const Index = () => (
  <div className={styles.root}>
    <AppBar position="static">
      <Toolbar>
        <IconButton
          className={styles.menuButton}
          color="inherit"
          aria-label="Menu"
          onClick={handleClick}
        >
          <MenuIcon />
        </IconButton>
        <Typography variant="h6" color="inherit" className={styles.grow}>
          Example
        </Typography>
        <Button color="inherit" style={{ right: "0px", position: "absolute" }}>
          Login
        </Button>
      </Toolbar>
    </AppBar>
    {drawer}
  </div>
);

【问题讨论】:

    标签: javascript material-ui next.js


    【解决方案1】:

    我不确定您在哪里声明了 drawerOpened 变量。 无论哪种方式,一旦你交换了drawerOpened 的值,drawer 的属性就发生了变化,无需篡改drawer.props.open

    const handleClick = e => {
      e.preventDefault();
      drawerOpened = !drawerOpened;
    };
    

    需要指出的另一件事,理想情况下,Index 应该是具有state 的 React 类(不是功能组件)。 drawerOpen 将存储在 state 中,并作为道具传递给 drawerhandleClick 将是 setStatedrawerOpened

    class Index extends React.Component {
      state = {drawerOpened: false}
    
      handleClick = e => {
        e.preventDefault();
        this.setState(prevState => ({
          drawerOpened: !prevState.drawerOpened
        }))
      };
    
      render() {
        return <div className={styles.root}>
          <AppBar position="static">
            <Toolbar>
              <IconButton
                className={styles.menuButton}
                color="inherit"
                aria-label="Menu"
                onClick={this.handleClick}
              >
                <MenuIcon/>
              </IconButton>
              <Typography variant="h6" color="inherit" className={styles.grow}>
                Example
              </Typography>
              <Button color="inherit" style={{ right: "0px", position: "absolute" }}>
                Login
              </Button>
            </Toolbar>
          </AppBar>
          <SwipeableDrawer open={this.state.drawerOpened}>
            <div tabIndex={0} role="button">
              {sideList}
            </div>
          </SwipeableDrawer>
        </div>
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多