javascript – 在React高阶组件中传播道具的目的是什么?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 在React高阶组件中传播道具的目的是什么?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1927字,纯文字阅读大概需要3分钟。
内容图文
![javascript – 在React高阶组件中传播道具的目的是什么?](/upload/InfoBanner/zyjiaocheng/789/feba555c06ba411689e832a704710391.jpg)
我正在尝试理解React的高阶组件结构,但是所有资源都假设您在编写时已经了解了扩展运算符在高阶组件中的用途:
BaseComponent {… this.props} {… this.state}.如果组件已经作为道具传递,为什么有必要分散这样的道具?
import React, { Component } from 'react';
const EnhanceComponent = BaseComponent => {
return class EnhancedComponent extends Component {
state = {
name: 'You have been enhanced'
}
render() {
return (
<BaseComponent {...this.props} {...this.state} />
)
}
}
};
export default EnhanceComponent;
解决方法:
答案直接在docs中解释:
Convention: Pass Unrelated Props Through to the Wrapped Component HOCs add features to a component. They shouldn’t drastically alter
its contract. It’s expected that the component returned from a HOC has
a similar interface to the wrapped component.HOCs should pass through props that are unrelated to its specific
concern. Most HOCs contain a render method that looks something like
this:
要理解这一点,你应该知道{… this.props}的作用.在你的情况下
const EnhanceComponent = BaseComponent => {
return class EnhancedComponent extends Component {
state = {
name: 'You have been enhanced'
}
render() {
return (
<BaseComponent {...this.props} {...this.state} />
)
}
}
};
export default EnhanceComponent;
EnhanceComponent HOC执行一个简单的操作,即向当前正在呈现的组件添加状态名称,因此当您使用此HOC时,您应该能够将原始组件所需的道具直接传递给它,而不是在HOC中使用它们,这是{… this.props}传播语法的用途.您可以阅读此答案,了解有关... works的更多详细信息
考虑使用类似的简单组件的情况
<MyComponent className='wrapper-container' onClick={this.handleClick} />
并定义为
class MyComponent extends React.Component {
render() {
const { className, onClick} = this.props;
...
}
}
现在如果你在这个组件上使用HOC就好了
const EnhancedMyComponent = EnhanceComponent(MyComponent);
你会渲染它
<EnhancedMyComponent className='wrapper-container' onClick={this.handleClick} />
现在,如果你不在你的HOC中写{… this.props},那么MyComponent将不再具有className和onClick作为道具
内容总结
以上是互联网集市为您收集整理的javascript – 在React高阶组件中传播道具的目的是什么?全部内容,希望文章能够帮你解决javascript – 在React高阶组件中传播道具的目的是什么?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。