While getting exactly the result you want is not possible, just because it is not a syntactically valid JSX. It is possible to make something looking quite similar to that:
// in render
<input type="text"
value={this.state.username}
onChange={setValue(this, 'username')}
/>
// add this method to the component
setValue(propName) {
return (e) => {
this.setState({ [propName]: e.target.value })
}
}
You can actually extract the setValue
function and reuse it with any other component:
// in render
<input type="text"
value={this.state.username}
onChange={setValue(this, 'username')}
/>
// somewhere outside of the component
function setValue(component, propName) {
return (e) => {
component.setState({ [propName]: e.target.value })
}
}
I believe I've seen some quite popular React forms handling library which was doing exactly this, but in a bit smarter way — they have cached the generated function to avoid creating a bunch of new function objects on each render. Just can't recall how was it named — there are too much new libs in the react world :)