Getting Input Values in React: Using Event Objects and Refs
This article demonstrates two ways to retrieve user-entered text in a React component—by accessing the event object's target value in an onChange handler and by defining a ref to read the input value directly—along with the supporting index.js setup.
Method One: Retrieve the input value through the event object. The component defines a state property text and an onChange handler hanChange that logs ev.target.value, updates the state with this.setState({ text: ev.target.value }), and then logs the updated state.
import React from 'react';
class Show extends React.Component {
state = { text: "" };
hanChange = ev => {
console.log(ev.target.value);
this.setState({ text: ev.target.value });
console.log(this.state.text);
};
render() {
return (
<div className="App">
<input type="text" onChange={ev => this.hanChange(ev)} />
<button className='red-btn' onClick={this.handleBtnClick}>add</button>
</div>
);
}
}
export default Show;Method Two: Use a ref to directly access the DOM node. The component creates a ref named ss on the input element and reads its value inside the aaaa method triggered by a button click.
import React, { Component } from 'react';
export default class Show extends Component {
constructor(props) {
super(props);
this.state = { acc: '' };
}
render() {
return (
<div>
<input ref="ss"></input>
<button onClick={this.aaaa.bind(this)}>提交</button>
</div>
);
}
aaaa() {
console.log(this.refs.ss.value);
}
}The accompanying index.js file imports React, ReactDOM, the Show component, and a CSS file, then renders the component inside React.StrictMode into the DOM element with id root. It also includes a comment about service workers.
import React from 'react';
import ReactDOM from 'react-dom';
import Show from './Show';
import './style.css';
ReactDOM.render(
<React.StrictMode>
<Show/>
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWAThe article concludes by previewing the next chapter on building a user login form with React and encourages readers to scan a QR code for further learning.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
