【问题标题】:How to call a class component using onclick event handler in react.js如何在 react.js 中使用 onclick 事件处理程序调用类组件
【发布时间】:2020-11-24 18:23:02
【问题描述】:

我有两个文件。 File1 是一个类组件,它使用导出返回一个类。 File2 是一个普通的函数组件。我在 File2 中有一个按钮,我想使用 onclick 事件处理程序来召唤我在 file2 中导入的 file1。 我包含了我的部分代码。

import Comment from './commentForm';

<Button type="button" outline onClick= {***I want to call comment here***}>
  Send Feedback
</Button>

注释是file1,按钮在file2

【问题讨论】:

  • 第一个文件是做什么的。请详细说明您的问题。不清楚。
  • 你想有条件地呈现评论吗?这方面的例子很多,不过你可以看看这个stackoverflow.com/questions/40477245/…
  • 显示两个文件,否则清楚地说明它的作用

标签: javascript html reactjs dom jsx


【解决方案1】:

您的按钮应该集成到一个包装组件中,请执行以下操作:

import React, { useState } from 'react'
import Comment from './commentForm';

const MyComponent = () => {
  const [displayed, setDisplayed] = useState()

  return (
    <div>
      { displayed && <Comment /> }
      <Button type="button" outline onClick={() => setDisplayed(true)}>
        Send Feedback
      </Button>
    </div>
  )
}

export default MyComponent

【讨论】:

    【解决方案2】:

    如果您要从另一个文件导入功能组件,您只需在 onClick 处理程序中添加变量即可。看看“评论”的实际作用可能会有用吗?

    import Comment from './commentForm';
    
    <Button type="button" outline onClick= {Comment()}>
      Send Feedback
    </Button>
    

    编辑:假设评论看起来像这样......

    const Comment = () -> {
       return comment
    }
    
    export default Comment
    

    【讨论】:

    • 我在调用类组件方法
    【解决方案3】:

    我假设,你想在另一个组件的点击处理程序中调用一个类组件方法, 假设你有

    1. 类组件:File1.jsx 中的 AClassComp
    2. 另一个组件(函数式或类):File2.jsx 中的 ParentComp

    您可以执行以下操作

    // File1.jsx
    
    Class AClassComp extends React.Component{
       constructor(){ ...... }
    
       someMethod1=()=>{}
       someMethod2=()=>{}
       ...
       render(){.....}
    }
    export default AClassComp;
    
     //File2
     import 'AClassComp' from './File1.jsx'
    
     function ParentComp(){
       const classCompRef = useRef(null);
    
       const onClickButton= (e)=> {
         // you can access the Class comp methods here 
         // or do what ever you want using the AClassComp instance
         classCompRef.current.someMethod1();
       }
    
       return (
        <>
        <AClassComp ref={classCompRef}/>
        <Button onClick={onClickButton}
        </>
       )
    
     }
    

    当你引用一个类组件时,它会返回它的实例。

    【讨论】:

      猜你喜欢
      • 2020-04-09
      • 1970-01-01
      • 2017-06-16
      • 2016-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多