>本教程解释了反应事件,受控组件和事件处理,演示了如何构建受控形式并从孩子到父组件发射数据。 让我们使用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
>,age
和password
>。
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
现在,在
<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> ); }
这完成了教程。 您已经学会了如何创建受控组件,处理事件并在React中发射事件。切记用实际的图像路径替换占位符图像路径。
以上是理解反应中的形式和事件的详细内容。更多信息请关注PHP中文网其他相关文章!