reactjs - 如何在反应中添加输入文本事件处理程序
问题描述
我报名参加了udemy的反应课程,并且有一个分配。那里给出了解决方案,但似乎反应库文件已更新,因此代码需要更改状态和偶数处理程序。在这里,我发布代码和我找到的答案,以防万一有人需要答案。
import React, { Component } from 'react';
import './App.css';
import UserInput from './UserInput/UserInput';
import UserOutput from './UserOutput/UserOutput';
class App extends Component {
state = {
username: 'jkr'
}
usernameChangedHandler = (event) => {
this.setState({username: event.target.value});
}
render() {
return (
<div className="App">
<ol>
<li>Create TWO new components: UserInput and UserOutput</li>
<li>UserInput should hold an input element, UserOutput two paragraphs</li>
<li>Output multiple UserOutput components in the App component (any paragraph texts of your choice)</li>
<li>Pass a username (of your choice) to UserOutput via props and display it there</li>
<li>Add state to the App component (=> the username) and pass the username to the UserOutput component</li>
<li>Add a method to manipulate the state (=> an event-handler method)</li>
<li>Pass the event-handler method reference to the UserInput component and bind it to the input-change event</li>
<li>Ensure that the new input entered by the user overwrites the old username passed to UserOutput</li>
<li>Add two-way-binding to your input (in UserInput) to also display the starting username</li>
<li>Add styling of your choice to your components/ elements in the components - both with inline styles and stylesheets</li>
</ol>
<UserInput
changed={this.usernameChangedHandler}
currentName={this.state.username} />
<UserOutput userName={this.state.username} />
<UserOutput userName={this.state.username} />
<UserOutput userName="Max" />
</div>
);
}
}
export default App;
解决方案
这里状态和事件处理程序的代码需要修改如下
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
username: 'jkr'
};
this.usernameChangedHandler=this.usernameChangedHandler.bind(this);
}
usernameChangedHandler(event) {
this.setState( { username: event.target.value});
}
这会做
礼貌:https ://reactjs.org/docs/forms.html https://reactjs.org/docs/hooks-state.html
推荐阅读
- r - 如何用整数和字符绑定行
- font-awesome - FontAwesome: css 内容: "\f468"; 对某些人不起作用
- azure - Traefik:部署在 Azure 上的 Swarm 模式中的错误网关
- android - 使用 Retrofit 时的 Android 错误
- html - 我可以将空 cookie 发送到浏览器吗?
- javascript - 如何在自适应卡片中捕获按钮文本(对于按下的按钮用户)
- marklogic - 如何为没有层次结构的普通 JSON 创建 TDE
- python - Pandas as_matrix() 到值保持列顺序
- azure-active-directory - 如何找到需要 Microsoft Graph“读取目录数据”权限的 Azure AD 应用程序的管理员同意 URL?
- node.js - FB 是否使用了不正确的 MQTT 协议?