javascript - react 高阶组件 : making assumptions about wrapped components

标签 javascript reactjs

假设我有一个函数来装饰一个 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/

相关文章:

javascript - 是否可以从firebase云函数node.js更新firestore中的map类型字段?

javascript - React redux 形式 FieldArray.map() 不起作用

javascript - 是否可以使用 for 循环生成 React props?

javascript - React - 如何通过 ref 应用样式

javascript - React 组件未在 History.push 上重新加载

javascript - 自动从外部源导入值,并使用它们进行计算

javascript - 防止同一函数触发两次

reactjs - 模块解析失败 : Unexpected token (7:5) You may need an appropriate loader to handle this file type

css - 与 Material UI 主题 react - 设置全局颜色变量

django - 为什么人们使用 Django 模板和 webpack 来连接 DRF 和 ReactJS?