• [React] Reduce Code Redundancy with Custom React Hooks


    In this lesson, we'll cover how to create a custom React hook for managing the state of any input. This is one of the most powerful features of react hooks as it allows you to easily share functionality in a reusable way.

    import React, { useState } from 'react'
    import ReactDOM from 'react-dom'
    
    import './styles.css'
    
    function useInput(defaultValue) {
      const [value, setValue] = useState(defaultValue)
    
      function onChange(e) {
        setValue(e.target.value)
      }
    
      return {
        value,
        onChange
      }
    }
    
    function App() {
      const name = useInput('')
      const age = useInput('')
      const email = useInput('')
    
      return (
        <div className="App">
          <h1>How to create a custom hook in React</h1>
    
          <label>
            <span>Name</span>
            <input {...name} /> <!-- the same as value={name.value} onChange={name.onChange}-->
          </label>
    
          <label>
            <span>Age</span>
            <input {...age} />
          </label>
    
          <label>
            <span>Email Address</span>
            <input {...email} />
          </label>
        </div>
      )
    }
    
    const rootElement = document.getElementById('root')
    ReactDOM.render(<App />, rootElement)
  • 相关阅读:
    用SecureCRT来上传和下载文件
    Linux指令--tar,gzip
    Linux指令--文件和目录属性
    Linux指令--which,whereis,locate,find
    Linux指令--head,tail
    Linux指令--more,less
    Linux指令--nl
    Linux指令--cat,tac
    Linux指令--touch
    Linux指令--cp
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10899357.html
Copyright © 2020-2023  润新知