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 ( this.hanChange(ev)} /> add ); } } 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 ( 提交 ); } 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( , 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-PWA
The 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.
Test Development Learning Exchange
Test Development Learning Exchange
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.