Design explained
I have a React
class with an arrow function that gets called from within child classes (modules). It's simply called saveData
and its purpose is to save an input value specific to each module to be saved to state
. So well, my default state has default props (static defaultProps
):
state = {
a : this.props.initialA,
b : this.props.initialB,
c : ...
}
And said saveData
function is a fat arrow function that's supposed to push the input value from the child class to a specific state property in the parent:
saveData = (val) => this.setState( {a : val} )
Each child class gets the saveData
function passed with JSX and has its own input. When a button is clicked I call the function with the value as parameter:
/* A child class */
pushData = (e) => {
e.preventDefault()
const val = this.refs.a.value
this.props.saveData(val)
}
render() {
return(
<input id='a' ref='a' ... />
<button onClick={this.pushData} ... />
)
}
This is all fine! Now for my concern
As you can see the state property a
is hard coded in the above examples. This is not what I want. I would want to have another parameter set the state property which in my head could be as simple as:
/* In parent class */
saveData = (prop, val) => this.setState( {prop : val} )
/* In child class */
pushData = (e) => {
...
const val = this.refs.a.value,
prop = a;
this.props.saveData(prop, val)
}
Now here are the problems I face with this approach:
- Did I understand right that arrow functions don't accept parameters? Because I totally do use
(e)
inpushData
and even(val)
insaveData
has worked for me before. - The crucial point: Whatever way I put it, the property in
this.setState({prop:val})
won't get assigned. It will just add a new property calledprop
even ifprop
is a variable, a parameter, or a rest parameter with a totally different content.
Is there a way to have ...setState({prop...
be assigned by the child class?
(Or am I just being overly complicated? Am I not thinking React
? I sometimes feel like thinking in React is like thinking $con"!"\˜*.ht"&&su20%+o?else{((())...())}of
)