zoukankan      html  css  js  c++  java
  • [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)
  • 相关阅读:
    HDU2059(龟兔赛跑)
    pat 1012 The Best Rank
    pat 1010 Radix
    pat 1007 Maximum Subsequence Sum
    pat 1005 Sign In and Sign Out
    pat 1005 Spell It Right
    pat 1004 Counting Leaves
    1003 Emergency
    第7章 输入/输出系统
    第六章 总线
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10899357.html
Copyright © 2011-2022 走看看