Javascript 在两个组件之间共享方法的最佳方式是什么?

Javascript 在两个组件之间共享方法的最佳方式是什么?,javascript,reactjs,Javascript,Reactjs,我有两个反应组分,我称之为R1和R2。有一个我需要的方法,我将调用M1,我需要从两者访问它 R2是R1的子组件 实际方法是: getID(){ let id = this.props.data.title; // replace spaces with _ id = id.replace(/ /g, '_'); // this is a special character and if you copy past it into the URL it w

我有两个反应组分,我称之为R1和R2。有一个我需要的方法,我将调用M1,我需要从两者访问它

R2是R1的子组件

实际方法是:

  getID(){

    let id = this.props.data.title;

    // replace spaces with _
    id = id.replace(/ /g, '_');

    // this is a special character and if you copy past it into the URL it will be substituted with %FOO
    id = id.replace(/’/g, '_');

    // youtube does not like double underscore in its comments so adjust to use double dash
    // now you can copy paste into youtube.
    id = id.replace(/#/g, '--');

    return id;
  }
我可以使用返回值。是否可以将
id
附加到
this.props
b.c.props传递给R2


显然有很多方法可以做到这一点,但什么是最好或最可靠的方法呢。这就是不容易出错或给其他开发人员造成混乱的代码。

将它们放在单独的js文件中,导出,然后导入到您需要和使用的组件中

假设要从两个react组件调用
getID()
,可以将函数作为属性传递给子组件,如下所示:

<R1 getID={getID}>
    <R2 getID={getID} />
</R1>

然后您可以从
R2
R1
调用
getID