Can we write the code in a shorter version?
For example:
function Account() {
const [code, setCode] = useState('')
return <input onChange={(e) => setCode(e.target.value)} />
}
Could we do it even more shorter like without creating new function? Like:
<input onChange={setCode} />
Some way?
Best!
You could use a custom useEventState
helper that wraps React's useState
and adds an additional setter to the tuple (array) it returns:
const useEventState = value => {
const [ initialValue, directSetter ] = useState(value);
return [
initialValue,
directSetter,
e => directSetter(e.target.value)
];
}
I think it makes sense to also still return the original setter that takes a value directly. If you only set code
through an onChange
event, you could even replace it with the e.target.value
one.
Here's a quick example (in which I added a button that uses the direct setter to show that's still useful to include):
function Account() { const [code, setCode, setCodeFromEvent] = useEventState(''); const toUpper = () => { setCode(code.toUpperCase()); } return ( <div> <input value={code} onChange={setCodeFromEvent} /> <p>Your code: {code}</p> <button onClick={toUpper}>To upper case</button> </div> ); } ReactDOM.render( <Account />, document.body );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script> <script> const { useState } = React; const useEventState = value => { const [ initialValue, directSetter ] = useState(value); return [ initialValue, directSetter, e => directSetter(e.target.value) ]; } </script>
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.