React:将 HOC 与回调作为 props 连接

React: connected HOC with with callback as props

我有几个“哑”组件。我正在尝试制作一个 higher-order 组件,将它们连接到 Redux 存储,并将回调函数作为道具传递。 child 组件将调用此回调函数以响应单击事件。

我正在为范围而苦苦挣扎。回调函数需要 setState 并派发一个 Redux 动作。

这是不起作用的:

//Child Component
class Child extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return <button onClick={this.props.callbackFunc}>Click</button>;
  }
}

//callback function
clickCallback(e){
  this.setState({foo: "bar"});
  this.props.dispatch(
    someReduxAction({boo: "baz"})
  );
}

const WithCallbackChunk = (Comp, callback) => {
  return class extends React.Component {
    constructor(props){
      super(props);
      this.callback = callback.bind(this);
    }
    render() { return <Comp callbackFunc={callback} {...this.props} />; }
  }
}

   
//connected comp
const ConnectedChunk = function(comp){
  return connect(
    null,
    {someReduxAction}
  )(WithCallbackChunk(comp));
}

const ConnectedCallbackComp = ConnectedChunk(Child);

export { ConnectedCallbackComp }

我无法在回调中获得正确的 setStateprops.dispatch 范围。

提前致谢!

更新/解释

一些人询问了 WithCallbackChunk 的目的。我正在尝试将表示逻辑与表单处理分开。

我的应用程序允许用户构建自定义表单。有一个显示表单预览的编辑模式,表单的每个“块”都是上面简化示例中的 Child 组件。当该表单发布时,那些 Child 组件(构成表单)需要变得交互并连接到 Redux 存储。

我试图通过重复使用“哑”表示组件来编辑 实时表单上下文(因为它们是相同的)来保持干燥。但是只有在实时上下文中才需要表单处理。 Child 组件在两种情况下都具有所有 Redux 操作似乎很混乱,所以我试图弄清楚如何通过 props 传递该功能。

我的目标是让 Child 组件只定义 UI,然后让两个不同的“包装器”HOC 组件为每个各自的上下文提供附加功能。显然,我没弄对。也许我在以错误的方式思考这个问题?我欢迎有关更好的方法的反馈或建议。

另一种总结方式是,我正在为 React 的 one-way 数据流而苦苦挣扎。 (信息只“向下”流向 children。)我试图将上下文逻辑从 HOC 向下传递。但是 Child 组件是唯一知道何时调用它的组件(因为它定义了 UI)

您将错误的回调传递给了包装组件。通过内部组件的 this 与传递给 HOC 的那个绑定。

const withCallback = (WrappedComponent, callback) => {
  class BaseContainer extends Component {
    constructor(props) {
      super(props);
      this.callback = callback.bind(this);
    }
    
    render() {
      return (
        <WrappedComponent
          callbackFunc={this.callback} // <-- pass the bound callback to this component
          {...this.props}
        />
      );
    }
  }

  return BaseContainer;
};

使用 redux 进行组合时,不要忘记将回调传递给 withCallback HOC。

const ConnectedChunk = connect(
  null,
  {someReduxAction}
)(withCallback(comp, callback));