我有两个 React 组件,我称之为 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
bc 道具传递到 R2。
显然有很多方法可以做到这一点,但是什么是最好或最强大的方法。 这是不容易出错或给其他开发人员造成混淆的代码。
将它们放在单独的js文件中并导出,然后导入到您需要和使用的组件中。
假设你想从两个 react 组件调用getID()
,你可以将函数作为属性传递给子组件,如下所示:
<R1 getID={getID}>
<R2 getID={getID} />
</R1>
然后,您将能够从R2
和R1
呼叫getID