【问题标题】:React : Cannot read property 'style' of undefined反应:无法读取未定义的属性“样式”
【发布时间】:2021-04-24 04:52:46
【问题描述】:

所以,我有这个代码,在反应:

const sidebar = document.getElementsByClassName("pro-sidebar");

此外,我尝试使用更改宽度值

function openNav() {
sidebar.style.width = "250px";}

onClick={closeNav} 在按钮上,但是当我尝试按下按钮时,它给了我下一个错误:TypeError: Cannot read property 'style' of undefined.

为什么??

【问题讨论】:

  • 你读错了吗?
  • 当你登录sidebar,你会得到什么?

标签: css reactjs typescript


【解决方案1】:

我们不会在 React 中像这样手动操作 DOM。做这样的事情。

  return (
    <div style={styles.container} />
  )

...

let styles = {
  container: {
    width: '20px'
  }
}

您可以在宽度上使用字符串插值来通过您的函数以编程方式更改它。

【讨论】:

  • 还有,等等,当我按下按钮时,我该怎么做才能改变那个witdh?
  • @MaresGabriel 将状态与宽度一起使用,当用户单击按钮时更改状态。使用字符串插值引用样式对象中的状态
猜你喜欢
  • 2019-02-13
  • 1970-01-01
  • 1970-01-01
  • 2022-10-08
  • 2021-08-04
  • 2017-01-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
相关资源
最近更新 更多