I have a scenario where I have two components that both use a TagInput
component I've written. Unfortunately, there are a lot of callbacks that the TagInput
needs, for tag adding, creation, removal, etc. So the code looks something like this:
<ComponentOne
onTagAdd={this.tagAdd}
onTagCreate={this.tagCreate}
onTagDelete={this.tagDelete}
onTagSetAll={this.tagSetAll}
/>
<ComponentTwo
onTagAdd={this.tagAdd}
onTagCreate={this.tagCreate}
onTagDelete={this.tagDelete}
onTagSetAll={this.tagSetAll}
/>
On top of any other props these two components need, that could amount to quite a long list.
My question is, is there a much better way to structure this? The only workaround I can think of is to have a single callback, like so:
<ComponentOne
onTagAction={this.handleTagAction}
/>
<ComponentTwo
onTagAction={this.handleTagAction}
/>
And then an action and arguments are passed to the callback:
handleTagAction = (action, args) => {
switch (action) {
case 'add':
break;
case 'create':
break;
// ...
}
};
Is there a better way I'm not thinking of?
You could also have a single object, something like
const tagActions = {
add : this.tagAdd,
create : this.tagCreate,
delete : this.tagDelete,
setAll : this.tagSetAll,
}
and then pass tagActions
as a single prop to your components. From your component, you could then call the method based on the use-case, for example this.props.tagActions.add()
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.