5

I am trying to create an HOC which makes a regular functional component »Touchable«.

So I have that an HOC like that:

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

  return T;
}

Another Component like so:

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

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

Using this like so:

<Button>Hallo</Button>

results in (react developer Panel):

<Button onTouchStart={…}>
  <div>…&lt;/div>
</Button>

But what I really would like to have is:

<Button>
  <div onTouchStart={…}>…&lt;/div>
</Button>

I have tried to clone the Instance, but somehow I have no luck. How can I do that?

4

2 回答 2

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>

于 2017-11-21T10:04:59.373 回答
1

您可以使用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;
}
于 2017-11-21T10:04:37.040 回答