首页 > web前端 > css教程 > 理解反应中的形式和事件

理解反应中的形式和事件

Jennifer Aniston
发布: 2025-03-04 09:35:10
原创
296 人浏览过

>本教程解释了反应事件,受控组件和事件处理,演示了如何构建受控形式并从孩子到父组件发射数据。 让我们使用React创建一个用户配置文件表格。

首先,创建一个新的React应用程序。 位于UserProfile>中的src/UserProfile.js组件为用户配置文件详细信息提供了一种表单。 将其导入您的根部组件(src/App.js):

>
import UserProfile from './UserProfile';

function App() {
  return (
    <div classname="App">
      <userprofile></userprofile>
    </div>
  );
}

export default App;
登录后复制

使用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;
}
登录后复制

渲染表最初将不符合应用程序状态。 要将表单输入连接到状态,我们将使用事件处理程序。

>

>反应事件

React事件是由用户交互或系统事件触发的操作(单击,键盘,页面加载等)。 为了处理输入更改,我们将使用onChange>事件。 修改name>UserProfile.js>的输入:

>
<input id="name-field" type="text" value="{name}" onchange="{(e)"> setName(e.target.value)}
/>
登录后复制
同样,使用其各自的状态变量和

挂钩更新email>,agepassword>。 useState登录状态,将函数添加到

>:

> UserProfile.js

>将提交按钮更新为
const logState = () => {
  console.log(name);
  console.log(email);
  console.log(age);
  console.log(password);
};
登录后复制

logState

>单击“提交”日志将表单数据记录到控制台。 这演示了双向数据绑定:视图中的更改更新状态,状态更改更新视图。
<button onclick="{logState}">Submit</button>
登录后复制
发射事件

>要将数据从子(

)发送到父(

),我们会发出一个事件。 添加一个

函数到UserProfile>:App> emit UserProfile.js>将提交按钮更新为

const emit = () => {
  props.callback({ name, email, age, password });
};
登录后复制

emit现在,在

>中,添加一个回调函数,并将其作为prop将其传递给
<button onclick="{emit}">Submit</button>
登录后复制
>:

>:App.js 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>
  );
}
登录后复制

Understanding Forms and Events in React Understanding Forms and Events in React 这完成了教程。 您已经学会了如何创建受控组件,处理事件并在React中发射事件。切记用实际的图像路径替换占位符图像路径。Understanding Forms and Events in React

以上是理解反应中的形式和事件的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板