Reputation: 41
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>
Upvotes: 2
Views: 4833
Reputation: 743
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
Upvotes: 0
Reputation: 153
When you use arrow functions there is no need to bind.
const onChange = (val)=>{
console.log(val)// comment
}
<input type="text"
onChange={() => onChange("comment")}
/>
Upvotes: 2
Reputation: 4938
Since onChange
runs on every keypress, you're attaching the quotation
marks to every keypress.
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')}
/>
Upvotes: 1