首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在react中添加输入文本事件处理程序

如何在react中添加输入文本事件处理程序
EN

Stack Overflow用户
提问于 2021-02-26 18:06:42
回答 1查看 79关注 0票数 0

我在udemy注册了一个react课程,有一个任务。这里给出了解决方案,但似乎react库文件已经更新,因此代码需要针对state和evenhandler进行更改。在这里,我发布了代码和我找到的答案,以防有人需要答案。

代码语言:javascript
复制
    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;
EN

回答 1

Stack Overflow用户

发布于 2021-02-26 18:06:42

这里需要修改状态和事件处理程序的代码,如下所示

代码语言:javascript
复制
    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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66383761

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档