调用事件处理程序(ReactJS)中的外部函数



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

我只是想在点击时运行一个外部函数,关键是我还想把一些状态作为道具传递给外部函数。

下面的示例代码:

child.js

import React from 'react';
export const SomeFunction =  (props) => {
//some logic to invoke
};

parent.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>
</>
);

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

SomeFunction({ state });

然后你可以做:

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

最新更新