加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 为什么要在React组件的道具中传递回调而不是使用reac

发布时间:2020-12-15 16:16:09 所属栏目:百科 来源:网络整理
导读:为什么回调(或redux的调度)在组件的道具中传递而不是总是使用react-redux连接函数是常见的? 作为道具的调度(或调度包裹的功能): // somewhere.js,calling Component in JSX with onButtonClick as propsComponent onButtonClick={someFunction}/// compone
为什么回调(或redux的调度)在组件的道具中传递而不是总是使用react-redux连接函数是常见的?

作为道具的调度(或调度包裹的功能):

// somewhere.js,calling Component in JSX with onButtonClick as props
<Component onButtonClick={someFunction}/>

// component.js
const Component = ({onButtonClick}) => <Button onClick={onButtonClick}>{'do something'}</Button>

连接功能:

// somewhere.js,calling Component in JSX without giving props
<Component/>

// component.js
const Component = ({onButtonClick}) => <Button onClick={onButtonClick}>{'do something'}</Button>
const mapDispathToProps = (dispatch,ownProps) => {
   return {
            onButtonClick: dispatch(someFunction)
          }
}
connect(mapDispathToProps)(Component)

解决方法

不同之处在于“表现”和“容器”组件,以前也称为智能和哑组件.容器组件是您“连接”的组件,而表示组件是刚接收道具的组件.

我将由redux的创建者Dan Abramov链接到this Medium article.

引用福利部分:

  • Better separation of concerns. You understand your app and your UI better by writing components this way.
  • Better reusability. You can use the same presentational component with completely different state sources,and turn those into separate container components that can be further reused.
  • Presentational components are essentially your app’s “palette”. You can put them on a single page and let the designer tweak all their variations without touching the app’s logic. You can run screenshot regression tests on that page.
  • This forces you to extract “layout components” such as Sidebar,Page,ContextMenu and use this.props.children instead of duplicating the same markup and layout in several container components.

根据我的个人经验,强迫自己使用这种风格确保我的组件更“理智”,更容易理解/维护.欢迎您不要使用此样式,但是当您遇到问题时,您可能需要重构以使用此方法来更好地分离关注点.

如果我在没有Dan帮助的情况下进行总结,我会这样说:连接到整个地方会让你对组件中每个道具的来源感到困惑.如果你强迫自己只在非常特定的地方连接(在我的项目中,我倾向于在页面级别和根级别连接),那么你总是会知道事情的来源,这有助于在出现问题时进行调试.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读