假设我有一个函数来装饰一个 React 组件类,其行为可以通过键盘在项目列表中导航,如下所示:
function MakeNavigable(ListComponent) {
class NavigableComponent extends React.component {
handleListKeydown(event) {
const listLength = this.refs.list.getListLength();
if (event.keyCode === 40 && this.state.focusedRow < listLength - 1) {
// handle down arrow
this.setState({ focusedRow: this.state.focusedRow + 1 });
}
// handle other keys here...
},
render() {
return (
<ListComponent onListKeydown={this.handleListKeydown} ref="list" />
);
},
}
return NavigableComponent;
}
请注意,我正在调用包装组件 getListLength()
上的一个方法,这意味着我必须假设 ListComponent
公开了这样一个方法。
确保这样的函数只接受组件类来包装具有所需实例属性或方法的最佳方法是什么?像这样依赖于从包装组件中获取信息甚至是对高阶组件的有效使用吗?如果没有,还有什么选择?导航行为可以由 mixin 提供,但根据 React docs :
Unfortunately ES6 launched without any mixin support. Therefore, there is no support for mixins when you use React with ES6 classes. Instead, we're working on making it easier to support such use cases without resorting to mixins.
最佳答案
What's the best way to ensure that a function like this only accepts component classes to wrap that have the required instance properties or methods?
您不能确保高阶组件只会采用具有属性/功能的组件。
Is it even a valid use of a higher-order component to depend on getting information from the wrapped component like this?
不,这不是真正有效的用途。
If not, what is the alternative?
您应该将 getList
代码重构到高阶组件中,然后您就不需要要求它存在于子组件上。
关于javascript - react 高阶组件 : making assumptions about wrapped components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36611611/