在 React 中的组件之间共享功能的正确方法 [英] Correct way to share functions between components in React

查看:31
本文介绍了在 React 中的组件之间共享功能的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个组件,它们都需要做同样的事情.(一个简单的函数,它映射到他们的子组件并对每个组件做一些事情).目前我正在每个组件中定义这个方法.但我只想定义一次.

I have multiple components which all need to do the same thing. (A simple function which maps over their child components and does something to each one). At the moment I am defining this method in each of the components. But I only want to define it once.

我可以在顶级组件中定义它,然后将其作为道具传递.但这感觉不太对.它更像是一个库函数而不是一个道具.(在我看来).

I could define it in the top level component and then pass it down as a prop. But that doesn't feel quite right. It is more a library function than a prop. (It seems to me).

这样做的正确方法是什么?

What is the correct way of doing this?

推荐答案

如果你使用像 browserify 这样的东西,那么你可以有一个外部文件,即util.js 导出一些实用函数.

If you use something like browserify then you can have an external file i.e util.js that exports some utility functions.

var doSomething = function(num) {
 return num + 1;
}

exports.doSomething = doSomething;

然后根据需要要求它

var doSomething = require('./util.js').doSomething;

这篇关于在 React 中的组件之间共享功能的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆