React应用程序返回null元素?

我有一个反应模式,呈现login和注册forms。 在窗体上,有一个按模式login提交button的IDbutton。 当我做

document.getElementById('modal-sign-in-submit-button'); 

它返回一个types错误,说这样的元素不存在…

 TypeError: document.getElementById(...) is null 

有没有一个包或解决方法,使其识别在HTML中的button?

这在控制台上工作正常,但是当我尝试访问由React在不同脚本中呈现的元素时,它不会find这样的元素。 (可能是由于它还没有生成)。

以下是该部分的来源,

 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="(?=.*[AZ]).{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; 

它看起来不像你正在创build一个ID为“submit-button”的button。 你正在寻找一个不存在的button。 尝试input以下内容:

 document.getElementById('modal-sign-in-submit-button'); 

如果你正在寻找一个框架,可以让你识别DOM上的元素,我会推荐jQuery的开发目的。 请注意,你应该尽量避免使用jQuery,因为它很沉重,而且毫无意义。

我也想build议您尝试使用lambdaexpression式或胖箭头函数this.openModal&this.closeModal。 这将允许您保留“this”的上下文而不使用.bind()。 显而易见的好处是:改进的代码可读性和“this”的显式绑定。

这里是一个例子:

 openModal() => { this.setState({ open: true }); closeModal() => { this.setState({ open: false }); 

我希望有帮助!

这是一个noob问题,但我find了一个解决scheme,实现我想要的。 它是在类本身中创build函数,然后将其绑定到构造函数。

所以,

 constructor() { super(); this.state = { open: false }; this.openModal = this.openModal.bind(this); this.closeModal = this.closeModal.bind(this); this.submit = this.submit.bind(this); } submit() { const submit = document.getElementById('modal-sign-up-submit-button'); const email = document.getElementById('modal-sign-up-mail-input').value; const pass = document.getElementById('modal-sign-up-password-input').value; const promise = firebase.auth().createUserWithEmailAndPassword(email, pass); promise.then(e => window.location.href="index.html"); promise.catch(e => console.log(e.message)); firebase.auth().onAuthStateChanged(firebaseUser => { if(firebaseUser) { this.setState({open: false}); console.log("hi"); } }); } render() { return( <button className="modal-button" id="modal-sign-up-submit-button" onClick={this.submit}>Submit</button> ) }