[英]Limiting prop-passing into React components
我有一个场景,我有两个组件都使用我编写的TagInput
组件。 不幸的是, TagInput
需要很多回调,用于标记添加、创建、删除等。因此代码如下所示:
<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}
/>
除了这两个组件需要的任何其他道具之外,这可能是一个很长的清单。
我的问题是,有没有更好的方法来构建它? 我能想到的唯一解决方法是进行单个回调,如下所示:
<ComponentOne
onTagAction={this.handleTagAction}
/>
<ComponentTwo
onTagAction={this.handleTagAction}
/>
然后一个动作和参数被传递给回调:
handleTagAction = (action, args) => {
switch (action) {
case 'add':
break;
case 'create':
break;
// ...
}
};
有没有更好的方法我没有想到?
你也可以有一个对象,比如
const tagActions = {
add : this.tagAdd,
create : this.tagCreate,
delete : this.tagDelete,
setAll : this.tagSetAll,
}
然后将tagActions
作为单个 prop 传递给您的组件。 从您的组件中,您可以根据用例调用该方法,例如this.props.tagActions.add()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.