简体   繁体   中英

How to onChange event method pass additional parameter by React hooks

I need to output modified value. Say I'm inputting: hello world, and I need this result: "hello world" (with quotation marks). I can do it with class-component but I failed with Hooks. What is wrong in my code?

 const { useState } = React; const App = () => { const [user, setUser] = useState(''); const onChange = (a, b, event) => { setUser(a + event.target.value + b); }; return ( <form> <h3>Username is: {user}</h3> <input type="text" value={user} onChange={onChange.bind(null, '"', '"')} /> </form> ); }; ReactDOM.render(<App />, document.getElementById("root"));
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>

PROBLEM

Since onChange runs on every keypress, you're attaching the quotation marks to every keypress.

SOLUTION

Rather than putting your quotation marks on your state. Attach the quotation marks in your JSX.

import React, { useState } from 'react';

const App = () => {
  const [user, setUser] = useState('');

  const onChange = (event) => {
    setUser(event.target.value)
  };

  return (
    <form>
      <h3>Username is: {user ? `"${user}"`: ''}</h3>
      <input
        type="text"
        value={user}
        onChange={onChange} />
    </form>
  );
};
export default App;

passing extra arguments from input field

<input
   onChange={e => onChange(e, 'hello, 'world')}
/>
When you use arrow functions there is no need to bind. 
 const   onChange = (val)=>{
    console.log(val)// comment
    }

    <input type="text"
       onChange={() => onChange("comment")}
    />

i use coffeescript, you can think the -> as function or =>, if we Passing a parameter to an onClick event handler in functional component by loop:

onClick = (n, x) -> ->
    setcheckindex n
    x()
<Boxr onClick={onClick n, x.onClick} /> for x,n in g

i have send the loopindex by n, and send a function by x.onClick

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