React HOC-add包含Component的事件监听器

时间:2017-11-21 09:53:44

标签: reactjs higher-order-components

我正在尝试创建一个HOC,它创建一个常规功能组件»Touchable«。

所以我有这样一个HOC:

const Touchable = (Component, handler) => {
  const T = ({props, children}) => {
    const Instance = React.createElement(
      Component, 
      {
        ...props,
        onTouchStart: (e) => handler.touchStart(e),
        /*more listeners*/
      }, children);
  }

  return T;
}

另一个组件如此:

const Button = ({props, children}) => <div>…</div>;

export default Touchable(Button, {touchStart: () => {}});

像这样使用:

<Button>Hallo</Button>

结果(反应开发者小组):

<Button onTouchStart={…}>
  <div>…</div>
</Button>

但我真正想要的是:

<Button>
  <div onTouchStart={…}>…</div>
</Button>

我试图克隆实例,但不知怎的,我没有运气。我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

你不能只返回没有Component部分的React.createElement吗?

类似的东西:

const TouchableHOC = (Component, handler) =>
  (props) =>
    <Component
      {...props}
      onClick={(event) => handler.touchStart(event)}
    />

const YourComponent = ({ children, onClick }) =>
  <button onClick={onClick}>{children}</button>


const EnhancedComponent = TouchableHOC(
  YourComponent,
  { touchStart: () => console.log('touchStart') }
)

const WithoutRest = TouchableHOC(
  'button',
  { touchStart: () => console.log('touchStart') }
)

const App = () =>
  <div>
    <EnhancedComponent>
      Click-me
    </EnhancedComponent>
    <WithoutRest>
      No props at all
    </WithoutRest>
  </div>

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

答案 1 :(得分:0)

您可以使用React.cloneElement克隆children并为其附加自定义道具

const Touchable = (Component, handler) => {
  const T = ({props, children}) => {
    const Instance = React.createElement(
      Component, 
      props,
      React.cloneElement(children, {
           onTouchStart: (e) => handler.touchStart(e),
           /*more listeners*/
      });
    )
  }

  return T;
}