Answer the question
In order to leave comments, you need to log in
How else can you get input field values in react?
Playing around with React. I got to the login screen component, and the moment when you need to get the value of the input field when the button is pressed. I haven't come up with anything smarter than getElementById , but somewhere deep down, I have faith that React might see it a little differently.
So, what is the correct way to get the value of the input field in React.
Component Code
import React, {Component} from 'react'
import "./Screen.css"
import "./LoginScreen.css"
/**
* Экран логина
* @extends Component
*/
class LoginScreen extends Component {
render() {
return(
<div class="screen login_screen">
<div class="content">
<div>
<h1 align="center">Вход</h1>
<div class="inputFieldLabel">Логин</div>
<input class="inputField" id="login"/>
<div class="inputFieldLabel">Пароль</div>
<input class="inputField" id="password" type="password"/>
<button class="button" onClick={(e)=>{
let login = document.getElementById("login").value
let password = document.getElementById("password").value
console.log(`login: ${login}, password: ${password}`)
}}>Войти</button>
</div>
</div>
</div>
)
}
}
export default LoginScreen
Answer the question
In order to leave comments, you need to log in
import React, {Component} from 'react'
import "./Screen.css"
import "./LoginScreen.css"
/**
* Экран логина
* @extends Component
*/
class LoginScreen extends Component {
constructor(props) {
super(props);
this.loginRef = null;
this.passwordRef = null;
}
render() {
return(
<div class="screen login_screen">
<div class="content">
<div>
<h1 align="center">Вход</h1>
<div class="inputFieldLabel">Логин</div>
<input class="inputField" ref={ref => this.loginRef = ref} />
<div class="inputFieldLabel">Пароль</div>
<input class="inputField" type="password" ref={ref => this.passwordRef = ref} />
<button class="button" onClick={(e)=>{
console.log(`login: ${this.loginRef.value}, password: ${this.passwordRef.value}`)
}}>Войти</button>
</div>
</div>
</div>
)
}
}
export default LoginScreen
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question