首页 > 解决方案 > 在事件处理程序(ReactJS)中调用外部函数

问题描述

是否可以在事件处理程序中调用外部函数?

我只是想在点击时运行一个外部函数,更重要的是我还想将一些状态作为道具传递给外部函数。

下面的示例代码:

child.js

 import React from 'react';

 export const SomeFunction =  (props) => {
 //some logic to invoke
 };

父.js

import React, { useState } from 'react';

import { SomeFunction} from './external';

export default function Parent = () => {
const [state, setState] = useState({
        //some state here
});

const handleSubmit = (e) => {
e.preventDefault();

//IS SOMETHING LIKE THIS POSSIBLE???
SomeFunction();


};

return (
    <>
    <button onClick={handleSubmit}>Click me</button>
    </>
);

标签: reactjsimportevent-handlingreact-hooks

解决方案


当然,您需要做的就是在调用函数时正确地将父状态传递给函数

SomeFunction({ state });

然后你可以这样做:

export const SomeFunction = (props) => {
  console.log(props.state);
};

推荐阅读