我有一个第三方库提供了一些 React 组件,我想通过添加 onClick() 处理函数来扩展其功能。处理程序函数可以工作,但是我不知道如何让该组件侦听 onClick() 事件并在预期时间触发处理程序。第三方库的源代码不可用。有什么建议么?预先感谢!
我四处搜索,发现一些提到通过 props 将侦听器传递到基本 HTML 元素,但如果第三方源不可用,我不知道如何执行此操作。
这是我正在处理的内容:
import { ThirdPartyComponent } from "ThirdPartyLibrary"
function MyComponent() {
return (<>
<ThirdPartyComponent/>
</>)
}
export default function LargerApp() {
return (<>
Lorem Ipsum
<MyComponent
onClick={(e) => { alert('onClick event handled successfully') }}
))
/>
More text on the page
</>)
}
此处 onClick 作为 props 传递给您的组件:
<MyComponent
onClick={(e) => { alert('onClick event handled successfully') }}
))
/>
您的功能组件接收所有 props 作为参数:
function MyComponent({onClick}) {
// You can use your onClick function here
return (<div onClick={onClick /* Depending on the structure of the component you could wrap it in a div and give the div the onClick */}>
<ThirdPartyComponent onClick={onClick /*if the third Party component supports it you can pass it directly as a prop*/}/>
</div>)
}
这里充满了您传递点击事件的代码。
import { ThirdPartyComponent } from "ThirdPartyLibrary";
const ExtendedThirdPartyComponent = (props) => {
const { onClick, ...rest } = props;
return (
<ThirdPartyComponent {...rest} onClick={onClick}>
</ThirdPartyComponent>
);
}
export default function LargerApp() {
return (
<>
Lorem Ipsum
<ExtendedThirdPartyComponent
onClick={(e) => {
alert("onClick event handled successfully");
}}
/>
More text on the page
</>
);
}