javascript - React.JS - 我正在尝试将 .js 文件中的函数导入 .jsx 文件,但它仍然无法正常工作。无法读取 null 的属性“单击”
问题描述
我是 React 新手,并且已经设置了我的应用程序。到目前为止,我正在尝试创建一个标题,其中包含一个菜单,并在整个网站上进行。经过大量研究,我成功地做到了。现在我正在尝试做一个更复杂的菜单 - 悬停等。我目前唯一不能做的是我不能在点击类时使它们处于活动状态 - 我有代码,但我没有不知道如何正确整合它。
我已经通过 StackOverflow 查看了如何导入函数并尝试过,但无济于事。这是我的所有代码和错误:
页眉.jsx
import React, { Component } from 'react';
import './Header.css';
import './Header.js';
import {openPage} from './Header.js';
//import { Button, Navbar, Nav, NavItem, NavDropdown, MenuItem } from
'react-bootstrap';
class Header extends Component {
render() {
return (
<div>
<button class="tablink" onclick={openPage('Home', this, 'red')}>Home</button>
<button class="tablink" onclick="openPage('News', this, 'green')" id="defaultOpen">News</button>
<button class="tablink" onclick="openPage('Contact', this, 'blue')">Contact</button>
<button class="tablink" onclick="openPage('About', this, 'orange')">About</button>
<div id="Home" class="tabcontent">
<h3>Home</h3>
<p>Home is where the heart is..</p>
</div>
<div id="News" class="tabcontent">
<h3>News</h3>
<p>Some news this fine day!</p>
</div>
<div id="Contact" class="tabcontent">
<h3>Contact</h3>
<p>Get in touch, or swing by for a cup of coffee.</p>
</div>
<div id="About" class="tabcontent">
<h3>About</h3>
<p>Who we are and what we do.</p>
</div>
</div>
);
}
}
export default Header;
OpenPage 是我导入的功能,但不能正常工作。它给了我错误'无法读取属性'click' of null''> 23 | document.getElementById("defaultOpen").click();
这是 .js 文件:
function openPage(pageName, elmnt, color) {
// Hide all elements with class="tabcontent" by default */
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Remove the background color of all tablinks/buttons
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].style.backgroundColor = "";
}
// Show the specific tab content
document.getElementById(pageName).style.display = "block";
// Add the specific color to the button used to open the tab content
elmnt.style.backgroundColor = color;
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
我将不胜感激任何提示或帮助!我已经坚持了很长时间,真的很想让我的菜单正常工作。我是 React 和 Javascript 的新手,如果我犯了一个愚蠢的错误,请原谅!提前致谢!
解决方案
首先,在反应中你不使用属性onclick=""
。你应该使用onClick={}
.
然后,我认为您的问题与反应的工作方式有关。React 渲染到一个虚拟 DOM,在 react 完成对虚拟 DOM 进行更改后,它被渲染到实际 DOM。此外,渲染是异步完成的,因此使用document.getElementByID()
my 不会产生所需的结果。你应该改用 React Refs。看看这个 StackOverflow 问题:如何在 ReactJS 中手动触发点击事件? 这里也是文档页面
希望对你有帮助
推荐阅读
- azure - Azure 应用程序中缺少“应用程序服务日志”选项
- lambda - 具有基本身份验证的 AWS API 网关
- azure - 如何使用 powershell 或 API 根据 VM 大小获取 Azure 托管磁盘的成本?
- python - 在python中计算概率值的问题
- python - VS Code 不使用 Python 执行 Python 代码
- android - 获取 HorizontalScrollView 子项的宽度
- ruby-on-rails - 带 3D 安全的 Stripe 订阅不完整
- python - 如何根据python中提供的0和1矩阵生成矩阵组合?
- api - REVOLUT 业务 api 支付在 2 个账户之间失败
- python - 如何在python中读取文件扩展名为.accdb的Ms access DB表?