试图将登录功能添加到登录按钮,但是由于某种原因它说“无法读取null的属性'addEventListener'”,我不知道如何解决。
我添加了window.onload = function(){}
,它可以在我的其他组件上使用,但不适用于该组件。
问题就在这部分。
window.onload = function(){
document.getElementById("submit").addEventListener("click", function(){
UserLogin();
})
}
这是完整的代码:
import React from 'react';
import './App.css';
import * as firebase from 'firebase/app';
import 'firebase/auth';
import firebaseConfig from './Config';
//import { BrowserRouter as Router, Route, Link } from "react-router-dom";
firebase.initializeApp(firebaseConfig);
function UserLogin(){
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
//var errorCode = error.code;
//var errorMessage = error.message;
});
}
window.onload = function(){
document.getElementById("submit").addEventListener("click", function(){
UserLogin();
})
}
function Login(){
return(
<div class="start">
<h1>Login</h1>
<div class="input">
<input id="email" type="text" placeholder="email"></input>
<input id="password" type="password" placeholder="password"></input>
<button id="submit">Login</button>
</div>
</div>
)
}
export default Login;
答案 0 :(得分:1)
调用window.onload
时可能尚未呈现登录。
为什么不只使用按钮上的onClick属性?
import React from 'react';
import './App.css';
import * as firebase from 'firebase/app';
import 'firebase/auth';
import firebaseConfig from './Config';
//import { BrowserRouter as Router, Route, Link } from "react-router-dom";
firebase.initializeApp(firebaseConfig);
function UserLogin(){
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
//var errorCode = error.code;
//var errorMessage = error.message;
});
}
function Login(){
return(
<div class="start">
<h1>Login</h1>
<div class="input">
<input id="email" type="text" placeholder="email"></input>
<input id="password" type="password" placeholder="password"></input>
<button id="submit" onClick={UserLogin}>Login</button>
</div>
</div>
)
}
export default Login;
答案 1 :(得分:1)
如果您希望在组件完成加载后自动调用UserLogin
函数,则可以使用Hooks
(React 16.8中已添加)。 >
import React, {useEffect} from 'react';
function Login(){
useEffect(() => {
UserLogin();
});
return(
<div class="start">
<h1>Login</h1>
<div class="input">
<input id="email" type="text" placeholder="email"></input>
<input id="password" type="password" placeholder="password"></input>
<button id="submit">Login</button>
</div>
</div>
)
}