简体   繁体   中英

Can someone explain me how custom hooks get the data and in depth flow of custom hooks

//use Input HOOK

I want to know that how this custom hook work

import { useState } from "react";

export default initialValue => {
  const [value, setValue] = useState(initialValue);
  return {
    value,
    onChange: event => {
      setValue(event.target.value);
    },
    reset: () => setValue("")
  };
};


//todo form

How this onchange method work how it update the data even though no onchange function is write in this programm

import React from "react";
import TextField from "@material-ui/core/TextField";
import useInputState from "./useInputState";

const TodoForm = ({ saveTodo }) => {
  const { value, reset, onChange } = useInputState("");

  return (
    <form
      onSubmit={event => {
        event.preventDefault();
        saveTodo(value);
        reset();
      }}
    >
      <TextField
        variant="outlined"
        placeholder="Add todo"
        margin="normal"
        value={value}
        onChange={onChange}
      />
    </form>
  );
};

export default TodoForm;

view full programm Code Sandbox link

Functions in JS are treated like any other variable. So the de-structured onChange (in the component) is taking the reference for a function which is defined anonymously in the custom hook , which is then used by the onChange method of the TextField component. This is similar to how you pass variables by reference is JS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM