gpt4 book ai didi

javascript - 无法读取 null React 的属性 'style'

转载 作者:行者123 更新时间:2023-11-30 09:17:15 25 4
gpt4 key购买 nike

当我使用以下代码为侧边栏添加组件时,我遇到了错误:

Cannot read property 'style' of null

import React, { Component } from "react";
import "../css/sidebar.css";

class Sidebar extends Component {
state = {};

openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "250px";
}

closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft = "0";
}

render() {
return (
<div>
<div id="mySidenav" class="sidenav">
<a
href="javascript:void(0)"
class="closebtn"
onclick={this.closeNav()}
>
&times;
</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>

<div id="main">
<h2>Sidenav Push Example</h2>
<p>
Click on the element below to open the side navigation menu, and
push this content to the right.
</p>
<span
styles={{ fontSize: "30", cursor: "pointer" }}
onclick={this.openNav()}
>
&#9776; open
</span>
</div>
</div>
);
}
}

export default Sidebar;

错误在下面的部分吗?

document.getElementById("mySidenav").style.width = "0";

问题是什么?

如果有人能提供帮助,我们将不胜感激。

最佳答案

首先,在您的 DOM 完全加载之前无法访问文档元素,因此您需要添加一个检查元素是否已加载:

class Sidebar extends React.Component {
state = {};

//Here you are not binding your methods nor you are using the ES6 Arrow function so you need to change the code here also.
openNav = () => {
if (
document.getElementById("mySidenav") &&
document.getElementById("main")
) {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "250px";
}
};

closeNav = () => {
if (
document.getElementById("mySidenav") &&
document.getElementById("main")
) {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft = "0";
}
};

render() {
return (
<div>
<div id="mySidenav" class="sidenav">
//Here you are calling the function on initial render that is why you are getting the error. you need to pass the function like this in order to trigger it on an event.
<a href="javascript:void(0)" class="closebtn" onclick={this.closeNav}>
&times;
</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>

<div id="main">
<h2>Sidenav Push Example</h2>
<p>
Click on the element below to open the side navigation menu, and
push this content to the right.
</p>
<span
styles={{ fontSize: "30", cursor: "pointer" }}
//Same as above here also
onclick={this.openNav}
>
&#9776; open
</span>
</div>
</div>
);
}
}

更正后的组件将是这个。您应该了解有关 ES6 和类的一些概念。

关于javascript - 无法读取 null React 的属性 'style',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54181012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com