I'm new to react and its design pattern, so i tried writing a two way binding and create an onChange for my class and its child, and i was wondering if this is a good thing to do and if its the correct design pattern
I have done something like this :
class A extends Component {
state = {
BClassProperties: {
goldAmount: '1',
silverAmount: '2'
}
}
onBChange = (goldAmount, silverAmount) => {
const oldBClassProperties = this.state.BClassProperties;
let newBClassProperties = {...oldBClassProperties};
newBClassProperties.goldAmount = goldAmount;
newBClassProperties.silverAmount = silverAmount;
this.setState({BClassProperties: newBClassProperties})
}
render () {
return (
<B
goldAmount = {this.state.goldAmount}
silverAmount = {this.state.silverAmount}
onChange={this.onBChange}
/>
)
}
}
class B extends Component {
onGoldChange = (event) => {
this.props.onChange(event.target.value, this.props.silverAmount);
};
onSilverChange = (event) => {
this.props.onChange(this.props.goldAmount, event.target.value);
};
render () {
return (
<React.Fragment>
<input placeholder={"gold"} onChange={this.onGoldChange} />
<input placeholder={"silver"} onChange={this.onSilverChange} />
</React.Fragment>
)
}
}
Is this okay?, are there any better alternatives ?
Thanks.
Aucun commentaire:
Enregistrer un commentaire