[英]How to call a class component using onclick event handler in react.js
我有两个文件。 File1 是 class 组件,使用导出返回 class。 File2 是一个普通的 function 组件。 我在 File2 中有一个按钮,我想使用onclick事件处理程序来召唤我在 file2 中导入的 file1。 我包括我的部分代码。
import Comment from './commentForm'; <Button type="button" outline onClick= {***I want to call comment here***}> Send Feedback </Button>
注释为 file1,按钮位于 file2
您的按钮应该集成到一个包装组件中,执行以下操作:
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
我假设,您想在另一个组件的单击处理程序中调用 class 组件方法,假设您有
您可以执行以下操作
// 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}
</>
)
}
当您引用 class 组件时,它会返回其实例。
如果您从另一个文件导入功能组件,您可以简单地在 onClick 处理程序中添加变量。 看看“评论”实际上做了什么可能有用吗?
import Comment from './commentForm';
<Button type="button" outline onClick= {Comment()}>
Send Feedback
</Button>
编辑:假设评论看起来像这样......
const Comment = () -> {
return comment
}
export default Comment
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.