我有一个可以呈现登录和注册表单的 react 模式。 在表单上,有一个 id 为 modal-sign-in-submit-button 的按钮。 当我这样做时
document.getElementById('modal-sign-in-submit-button');
它返回一个类型错误,表示该元素不存在...
TypeError: document.getElementById(...) is null
是否有一个包或解决方法可以使其识别 html 中的按钮?
这在控制台上工作正常,但是当我尝试访问由 React 在不同脚本中渲染的元素时,它找不到这样的元素。 (可能是因为它尚未生成)。
以下是该部分的来源,
import React, { Component } from 'react';
import Modal from 'react-modal';
class SignInModalTrigger extends Component {
constructor() {
super();
this.state = {
open: false
};
this.openModal = this.openModal.bind(this);
this.closeModal = this.closeModal.bind(this);
}
openModal() {
this.setState({open: true});
}
closeModal() {
this.setState({open: false});
}
render () {
return (
<div>
<a className="navbar-items" onClick={this.openModal} href="#">Sign in</a>
<Modal className="sign-in-modal" isOpen={this.state.open}>
<h1 className="modal-title">Sign in</h1>
<div className="modal-inner-form">
<input className="modal-input" id="modal-sign-in-mail-input" type="email" placeholder="Enter your email here"/>
<br />
<br />
<input className="modal-input" id="modal-sign-in-password-input" type="password" placeholder="Enter your password here" pattern="(?=.*[A-Z]).{6,}"/>
<br />
<br />
<button className="modal-button" id="modal-sign-in-submit-button">Submit</button>
<br />
<br />
<button className="modal-button" onClick={this.closeModal}>Close</button>
</div>
</Modal>
</div>
);
}
}
export default SignInModalTrigger;
最佳答案
您似乎没有创建 id 为“submit-button”的按钮。您正在寻找一个不存在的按钮。尝试输入以下内容:
document.getElementById('modal-sign-in-submit-button');
如果您正在寻找一个允许您识别 DOM 上的元素的框架,我会推荐用于开发目的的 jQuery。请注意,您应该尽量避免使用 jQuery,因为它很重而且毫无意义。
我还想建议您尝试对 this.openModal 和 this.closeModal 使用 lambda 表达式或粗箭头函数。这将允许您保留“this”的上下文,而无需使用 .bind()。明显的好处是:提高了代码可读性和“this”的显式绑定(bind)。
这是一个例子:
openModal() => { this.setState({ open: true });
closeModal() => { this.setState({ open: false });
希望对您有所帮助!
关于javascript - React 应用程序在元素上返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40138553/