reactjs - 在事件处理程序(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>
</>
);
解决方案
当然,您需要做的就是在调用函数时正确地将父状态传递给函数
SomeFunction({ state });
然后你可以这样做:
export const SomeFunction = (props) => {
console.log(props.state);
};
推荐阅读
- ios - 使用 SKReferenceNode 引用的 SpriteKit 场景不加载自定义类
- node.js - Sinon stub request-promise 用于客户端单元测试
- codeigniter - [Codeigniter]多次上传不能插入数据库,不能上传到目录
- bootstrap-4 - Laravel - 如何在卡片和分页之间创建距离
- c# - 如何在 Python Waitress 服务器上调试(500)内部服务器错误?
- r - 用动态列总结 dplyr?
- python-2.7 - 如何在 boto3 python2.7 list dict 对象中搜索值 - list_tags_for_resource
- django - 为在 Apache 和 wsgi 上运行的 django 站点升级 python
- mysql - Mysql 多索引不适用于单个查询(Group By + Range Where 条件)
- android - 带有两个 TextView 的 RecyclerView 中的交叉淡入淡出动画