react初学者,有个问题不清楚:
点击按钮,执行this.calcAccount();
1.通过refs获取到子组件,并调用其实例方法test(),为什么会undefined呢?
注意点:此子组件是被Form.create()(ElectricityTemp)包装过,这是antdesign中的From组件提供的方法。
以下两个组件,去除了不必要的code.
父组件:ElectricityFees.tsx
class ElectricityFees extends React.Component<Iprops, Istate> {
constructor(props: any) {
super(props);
this.calcAccount = this.calcAccount.bind(this);
}
public calcAccount: (e: any) => void = (e: any) => {
const self = this;
this.props.rooms.forEach((_:object, i:number) => {
const a = self[`refs${i}`].current; **// 这里a是子组件,可是为什么没有test方法?**
a.test();
});
};
public render() {
const key: string = 'name';
this.props.rooms.forEach((_:object, i:number) => {
this[`refs${i}`] = React.createRef();
});
return (
<React.Fragment>
<Row gutter={24}>
{
this.props.rooms.map((_: object, i: number) => {
return (
<Col className="gutter-row" span={6} key={i}>
<WrappedTimeRelatedForm name={_[key]} ref={this[`refs${i}`]}/>
</Col>
)
})
}
</Row>
<Button onClick={this.calcAccount}>结算</Button>
</React.Fragment>
)
}
}
export default ElectricityFees;
子组件:WrappedTimeRelatedForm.tsx
class ElectricityTemp extends React.Component<Iprops, any> {
public test(){
console.log(this.props.name);
}
public render() {
return (
<Form>
...
</Form>
);
}
}
const WrappedTimeRelatedForm = Form.create()(ElectricityTemp);
export default WrappedTimeRelatedForm;