Home >Web Front-end >CSS Tutorial >Understanding Forms and Events in React
This tutorial explains React events, controlled components, and event handling, demonstrating how to build a controlled form and emit data from a child to a parent component. Let's create a user profile form using React.
First, create a new React app. The UserProfile
component, located in src/UserProfile.js
, renders a form for user profile details. Import it into your root component (src/App.js
):
import UserProfile from './UserProfile'; function App() { return ( <div classname="App"> <userprofile></userprofile> </div> ); } export default App;
Style the form using src/App.css
:
.App { text-align: left; margin-left: 20%; margin-right: 20%; } label { display: inline-block; margin-right: 1em; width: 4em; } input { width: 15em; }
The rendered form will initially be unbound to the application state. To connect the form input to the state, we'll use event handlers.
React events are actions triggered by user interactions or system events (clicks, key presses, page loads, etc.). To handle input changes, we'll use the onChange
event. Modify the name
input in UserProfile.js
:
<input id="name-field" type="text" value="{name}" onchange="{(e)"> setName(e.target.value)} />
Similarly, update the email
, age
, and password
inputs using their respective state variables and useState
hooks.
To log the state, add a function to UserProfile.js
:
const logState = () => { console.log(name); console.log(email); console.log(age); console.log(password); };
Update the submit button to call logState
:
<button onclick="{logState}">Submit</button>
Clicking "Submit" logs the form data to the console. This demonstrates two-way data binding: changes in the view update the state, and state changes update the view.
To send data from the child (UserProfile
) to the parent (App
), we'll emit an event. Add an emit
function to UserProfile.js
:
const emit = () => { props.callback({ name, email, age, password }); };
Update the submit button to call emit
:
<button onclick="{emit}">Submit</button>
Now, in App.js
, add a callback function and pass it as a prop to UserProfile
:
function App() { const [data, setData] = useState({}); const importData = (data) => setData(data); return ( <div classname="App"> <userprofile callback="{importData}"></userprofile> <p>Name: {data.name || "No name To Display"}</p> <p>Email: {data.email || "No email To Display"}</p> </div> ); }
Now, submitting the form will update the parent component, displaying the submitted data.
This completes the tutorial. You've learned how to create controlled components, handle events, and emit events in React. Remember to replace placeholder image paths with actual image paths.
The above is the detailed content of Understanding Forms and Events in React. For more information, please follow other related articles on the PHP Chinese website!