我将在下面展示两种样式,您需要根据组件的逻辑相互关联程度进行选择。
样式 1 - 相对相关的组件可以在./components/App.js...中使用回调引用创建,就像这样,在./components/App.js...
<SomeItem
ref={(instance) => {this.childA = instance}}
/>
<SomeOtherItem
ref={(instance) => {this.childB = instance}}
/>
然后你就可以像这样使用他们之间的共享功能了...
this.childA.investigateComponent(this.childB); // call childA function with childB as arg
this.childB.makeNotesOnComponent(this.childA); // call childB function with childA as arg
样式 2 - Util 类型的组件可以像这样创建,在./utils/time.js...
export const getTimeDifference = function (start, end) {
// return difference between start and end
}
然后它们可以像这样使用,在./components/App.js...
import React from 'react';
import {getTimeDifference} from './utils/time.js';
export default class App extends React.Component {
someFunction() {
console.log(getTimeDifference("19:00:00", "20:00:00"));
}
}
使用哪个?
如果逻辑是相对相关(它们只能在同一个应用中一起使用),那么您应该在组件之间共享状态。但如果你的逻辑是远相关(即数学工具、文本格式化工具),那么你应该制作和导入工具类函数。