我正在尝试实现Wizard用户可以使用以下模式使用的特定组件。
<Wizard {...wizardProps} onFinish={this.handleFinish}>
<WizardStep onValidate={() => this.componentARef.isValid()}>
<ComponentA onRef = { ref => (this.componentARef = ref)}/>
</WizardStep>
<WizardStep onValidate={() => this.componentBRef.isValid()}>
<ComponentB onRef = { ref => (this.componentBRef = ref)}/>
</WizardStep>
<WizardStep onValidate={() => this.componentCRef.isValid()}>
<ComponentC onRef = { ref => (this.componentCRef = ref)}/>
</WizardStep>
</Wizard>
现在考虑我们不能/不应该从父组件调用子组件的方法的react方式。在这里,我想isValid在每个组件中保留一个方法,该方法将Wizard在单击Next/Finish按钮时从父组件调用。React 方式建议将状态和逻辑移动到父组件。但是那样我将无法重用相同的组件,例如ComponentA在任何其他向导或任何其他地方,或者我将不得不在每个使用ComponentA. 使用ref或这种方法我可以轻松访问子组件的方法(isValid)。
截至今天(React 版本 16.6),我没有看到在react中根据需要使用此模式的任何陷阱。在 React 中使用这种模式可能会遇到什么问题?在这个特定示例中是否有更好的选择,我可以使用它isValid在步骤组件(例如ComponentA)中保留方法以供重用?