我正在尝试从父级调用子组件中的函数this.clickAddGoal(stageContent);
,虽然看起来一切正常但undefined
显示为class ParentClass extends Component
{
constructor(props, context)
{
super(props, context);enter code here
this.state = {stageContent: ''};
this.getStageContent = this.getStageContent.bind(this);
}
getStageContent = (stageId) =>
{
let stageContent = '';
switch (stageId)
{
case 1:
stageContent = this.props.data.PPYPL;
break;
case 2:
stageContent = this.props.data.I;
break;
case 3:
stageContent this.props.data.DH;
break;
case 4:
stageContent = this.props.data.R;
break;
}
this.clickAddGoal(stageContent);
this.setState({stageContent: stageContent});
}
renderComponents = () =>
{
return (
<div>
<ChildComponent
subjectContent={this.props.data.name}
onRef={click => this.clickAddGoal = click}
/>
</div>
);
}
}
render()
{
return (
<div style={style}>
<div className="performance-graph">
<div className="container">
<div className="row">
<div className="col-xs-3">
{}
</div>
</div>
<br/>
<div className='subject-unit'>
<StageBar
id={this.props.data.id}
subjectCode={this.props.data.area.color}
progressPercentage={this.props.data.percentageProgress}
onGetStage={this.getStageContent}
/>
{this.renderComponents()}
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) =>
{
return {
data: state.planAreaUnitRed,
};
};
export default connect(mapStateToProps, null)(ParentClass);`
import React, {Component} from 'react';
import {connect} from 'react-redux'
class ChildComponent extends Component
{
constructor(props)
{
super(props);
this.state = {editUnit: false, viewContentStage: false, autonomy:''};
}
componentWillMount()
{
this.handleToggle()
}
componentDidMount() {
this.props.onRef(this.handleToggle);
}
handleToggle = () =>
{
this.props.clearStageContent();
this.props.stageContent!=='' this.props.loadContentUnitStage(this.props.stageContent):'';
}
render()
{
return (
<div className='unit-content'>
<div className="container">
<div className="row">
<h3>
{this.props.subjectContent}
</h3>
<div style={{padding: '50px', fontSize: '24px'}}>
{this.props.stageContentData.content}
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) =>
{
return {
stageContentData: state.planAreaUnitRed.stageContent,
};
};
const mapDispatchToProps = (dispatch) =>
{
return {
loadContentUnitStage: (hash) =>
{
dispatch(planAreaUnitActions.fetchContentUnitStage(hash))
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(UnitContent);
子组件
{{1}}
我做错了吗?
答案 0 :(得分:0)
我知道的一种方法是,如果您尝试从父组件访问子组件,则可以在子组件本身中应用ref。喜欢
<ChildComponent
subjectContent={this.props.data.name}
ref={click => this.clickAddGoal = click}
/>
然后ref clickAddGoal
包含对底层子组件的引用。然后你可以从你的父组件处理它,如
this.clickAddGoal.handleToggle();