Javascript 如何通过HOC添加onMouseDown侦听器

Javascript 如何通过HOC添加onMouseDown侦听器,javascript,reactjs,react-hooks,styled-components,Javascript,Reactjs,React Hooks,Styled Components,嗨,我一直在尝试制作一个更高阶的组件,在提供的组件中添加一些状态和事件监听器,这样我就可以通过JS在单击/触摸时设置它们的动画。我想我离这里很远,这是漫长的一天,请原谅,如果这个代码是胡说八道 import React, { useEffect, useState } from 'react' const TouchAnimator = (child) => { const [animated, setAnimated] = useState(false); co

嗨,我一直在尝试制作一个更高阶的组件,在提供的组件中添加一些状态和事件监听器,这样我就可以通过JS在单击/触摸时设置它们的动画。我想我离这里很远,这是漫长的一天,请原谅,如果这个代码是胡说八道

import React, { useEffect, useState } from 'react'

const TouchAnimator = (child) => {
      const [animated, setAnimated] = useState(false);
      const [NewComponent, setNewComponent] = useState(child)

      const handleMouseDown = () => {
            setAnimated(true)
      }
      const handleMouseUp = () => {
            setAnimated(false)
      }

      useEffect(() => {
            setNewComponent(React.cloneElement(child, {animated: animated}));
      }, [animated, child])
      return (
            <NewComponent onMouseUp={handleMouseUp} onMouseDown={handleMouseDown}/>
      )
}

export default TouchAnimator
import React,{useffect,useState}来自“React”
const touch animator=(子项)=>{
const[animated,setAnimated]=使用状态(false);
常量[NewcomComponent,SetNewcomComponent]=useState(子级)
常量handleMouseDown=()=>{
设置动画(真)
}
const handleMouseUp=()=>{
设置动画(假)
}
useffect(()=>{
setNewComponent(React.cloneElement(子对象,{animated:animated}));
},[动画,儿童])
返回(
)
}
导出默认TouchAnimator
我得到一个错误,说: “警告:React.createElement:类型无效--需要字符串(对于内置组件)或类/函数(对于复合组件),但得到:。您是否意外导出了JSX文本而不是组件?”


有人能帮我做这件事吗?

首先,在你的例子中,这不是特别的

如果像这样使用它:

<TouchAnimator child={<SomeComponent />} />
但是在上面的例子中,
TouchAnimator
只是一个React组件

另外,我不确定是否使用
React.cloneElement
。或许,您可以使用下一个HOC示例:

const withTouchAnimator = (WrappedComponent) => {
  return (...props) => {
    const [animated, setAnimated] = useState(false);

    const handleMouseDown = () => {
      setAnimated(true);
    };
    const handleMouseUp = () => {
      setAnimated(false);
    };

    return (
      <WrappedComponent
        {...props}
        animated={animated}
        onMouseDown={handleMouseDown}
        onMouseUp={handleMouseUp}
      />
    );
  };
};
constWithTouchAnimator=(WrappedComponent)=>{
返回(…道具)=>{
const[animated,setAnimated]=使用状态(false);
常量handleMouseDown=()=>{
设置动画(真);
};
const handleMouseUp=()=>{
设置动画(假);
};
返回(
);
};
};
使用HOC:

const Element = ({ onMouseDown, onMouseUp }) => (
  <div onMouseDown={onMouseDown} onMouseUp={onMouseUp}>
    Element
  </div>
);

const TouchAnimatorExample = withTouchAnimator(Element);

<TouchAnimatorExample />
const元素=({onMouseDown,onmousedup})=>(
元素
);
const TouchAnimatorExample=withTouchAnimator(元素);

Ahhh,谢谢你的帮助!不客气!
const Element = ({ onMouseDown, onMouseUp }) => (
  <div onMouseDown={onMouseDown} onMouseUp={onMouseUp}>
    Element
  </div>
);

const TouchAnimatorExample = withTouchAnimator(Element);

<TouchAnimatorExample />