【问题标题】:can we able to specify on click on the component definition itself?我们可以指定单击组件定义本身吗?
【发布时间】:2022-01-08 06:03:16
【问题描述】:

我想创建一个带有 onclick 事件处理程序的组件(comp)。这应该由组件本身处理(即在 comp.js 文件中)。 如果我在父组件中使用它,我们不需要指定事件,但它由组件元素(comp 元素)处理。

这可能吗。任何想法来开发这个。

在 ParentComponent.js 当前行为中。

<NewComponent onClick={clickBehaviour}/>

我想要, 在 NewComponent.js 中

const NewComponent.js = ()=>{
    // Some code
    const clickBehaviour = () =>{
        // click behaviour
    }
}

在现行标准中是否可行?

【问题讨论】:

    标签: reactjs react-component


    【解决方案1】:

    为什么要在父组件中编写 onClick 事件? 您可以在 NewComponent.js 中轻松完成。 这样做:

    import React from 'react'
    
    function NewComponent() {
    
        const clickBehaviour = () =>{
            // click behaviour
        }
    
        return (
            <div onClick={clickBehaviour}>
                //some jsx here
            </div>
        )
    }
    
    export default NewComponent
    

    并在您想使用的任何地方使用而无需 onClick 事件:

    < NewComponent />
    

    我不能很好地理解你的情况,但你可以根据需要使用 forwardRef(也可以使用旧的 getElementById,但建议使用 forwardRef)。

    import React, { useRef } from "react";
    
    const NewComponent = React.forwardRef((props, ref) => (
      <div onClick={() => alert("div 2 clicked")} ref={ref}>
        div 2
      </div>
    ));
    export default function App() {
      const compRef = useRef(null);
      return (
        <div>
          <NewComponent ref={compRef} onClick={() => {
              compRef && compRef.current && compRef.current.click();
            }} />
        </div>
      );
    }
    

    【讨论】:

    • 我需要创建一个需要在多个地方使用的可拖动组件。我可以在 Component.js 文件上编写而不是在多个位置组件文件上编写 onclick,这样我就不必重复了
    • 我不能很好地理解你的情况,但我认为 forwardRef 是你想要的。我更新了我的答案,希望对你有帮助
    猜你喜欢
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多