为什么突变会使反应组件本身不可重用?
Why does mutation make a react component non-reusable on it's own?
所以我正在阅读关于 HOC 的 React 文档(可在此处找到:https://reactjs.org/docs/higher-order-components.html)并且有以下部分:
"Resist the temptation to modify a component’s prototype (or otherwise mutate it) inside a HOC."
function logProps(InputComponent) {
InputComponent.prototype.componentWillReceiveProps = function(nextProps) {
console.log('Current props: ', this.props);
console.log('Next props: ', nextProps);
};
// The fact that we're returning the original input is a hint that it has
// been mutated.
return InputComponent;
}
// EnhancedComponent will log whenever props are received
const EnhancedComponent = logProps(InputComponent);
"There are a few problems with this. One is that the input component cannot be reused separately from the enhanced component."
为什么变异的输入组件不被认为是可重用的,而包装的组件是?
编辑:如果您认为文档的这一部分只是胡说八道,如果有某种解释,我会接受它作为答案。
修改 InputComponent
的原型会改变 InputComponent
是 的定义,并且会影响 InputComponent
的每个实例。
如果您以私有的、封装的方式修改原型——即以一种没人知道的方式——那么没人知道 InputComponent
是什么,所以他们不能可靠地使用它.
所以我正在阅读关于 HOC 的 React 文档(可在此处找到:https://reactjs.org/docs/higher-order-components.html)并且有以下部分:
"Resist the temptation to modify a component’s prototype (or otherwise mutate it) inside a HOC."
function logProps(InputComponent) {
InputComponent.prototype.componentWillReceiveProps = function(nextProps) {
console.log('Current props: ', this.props);
console.log('Next props: ', nextProps);
};
// The fact that we're returning the original input is a hint that it has
// been mutated.
return InputComponent;
}
// EnhancedComponent will log whenever props are received
const EnhancedComponent = logProps(InputComponent);
"There are a few problems with this. One is that the input component cannot be reused separately from the enhanced component."
为什么变异的输入组件不被认为是可重用的,而包装的组件是?
编辑:如果您认为文档的这一部分只是胡说八道,如果有某种解释,我会接受它作为答案。
修改 InputComponent
的原型会改变 InputComponent
是 的定义,并且会影响 InputComponent
的每个实例。
如果您以私有的、封装的方式修改原型——即以一种没人知道的方式——那么没人知道 InputComponent
是什么,所以他们不能可靠地使用它.