zoukankan      html  css  js  c++  java
  • [React] Public Class Fields with React Components

    Public Class Fields allow you to add instance properties to the class definition with the assignment operator (=). In this lesson, we'll look at their use case for simplifying event callbacks and state initialization with a React component.

    Handle function:

    // Better
    handleClick = () => {
        ...
    }
    
    // Not good
    constructor() {
        super();
        this.handleClick = this.handleClick.bind(this);
    }
    
    handleClick() {
       ...  
    }

    Handle State:

    // Better
    state = {count: 0}
    
    // Not good
    constructor() {
        super();
        this.state = {count: 0};
    }

    Using puiblic field, we can actually remove 'constructor' because it is no longer necessary.

    class App extends React.Component {
      state = {clicks: 6}
    
      handleClick = () => {
        this.setState(prevState => {
          return {clicks: prevState.clicks + 1}
        })
      }
    
      render() {
        return (
          <div>
            <div>
              Click Count: {this.state.clicks}
            </div>
            <button
              onClick={this.handleClick}
            >
              Click Me!
            </button>
          </div>
        )
      }
    }
    
    ReactDOM.render(
      <App />,
      document.getElementById('root')
    )
  • 相关阅读:
    Spring boot 梳理
    Spring boot 梳理
    Spring boot 梳理
    观察者模式
    设计模式原则
    Spring MVC上传文件
    Spring MVC视图解析器
    Spring MVC中Action使用总结
    Spring MVC控制器
    Java并发 两个线程交替执行和死锁
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6297230.html
Copyright © 2011-2022 走看看