我正在尝试创建一个 HOC,使常规功能组件“可触摸”。
所以我有一个像这样的 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>
结果( react 开发小组):
<Button onTouchStart={…}>
<div>…</div>
</Button>
但我真正想要的是:
<Button>
<div onTouchStart={…}>…</div>
</Button>
我尝试过克隆实例,但不知何故我没有运气。我怎样才能做到这一点?
最佳答案
不能只返回没有 React.createElement
部分的 Component
吗?
类似于:
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>
关于reactjs - React HOC——向包装组件添加事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47410050/