[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)

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/10899357.html