经过大量的谷歌搜索,我找不到解决方案。我需要从父组件调用一个子函数。两者都是类组件。
一些代码
constructor(props) {
super(props)
this.childRef = React.createRef();
this.setAbilities();
}
渲染子组件
{this.props.enemyChamp.abilities.map(ab => (
<AbilityButton
ref={this.childRef}
onCast={(caster, ability)=>this.castAbility(caster, ability)}
index={this.abilities[ab].id}
/>
))}
我要调用的函数AbilityButton.js
castEnemyAbility = (ability, abIndex) => {
var caster = "enemy";
if(this.props.onCast(caster, ability)) {
this.startCooldown(abIndex);
this.cdTimer = setTimeout(() => {
}, this.getAb().coolDown)
}
}
导出父组件
export default connect(mapStateToProps, {
setAbilities,
doDamage, heal,
regenMana, regenHealth
}, null, {forwardRef: true})(战斗);
我尝试了有无{forwardRef: true}
,尝试了另一种渲染子组件的方法:
<AbilityButton
wrappedComponentRef={ref => this.childRef = ref}
onCast={(caster, ability)=>this.castAbility(caster, ability)}
index={this.abilities[ab].id}
/>
我尝试了很多组合,经过大量的反复试验和谷歌搜索,我决定寻求帮助。
this.childRef.current
总是返回null
。有什么建议吗?我厌倦了尝试