react beginners, there is a question that is not clear:
Click the button to execute this.calcAccount ();
1. Why is it undefined when you get the child component through refs and call its instance method test (),?
Note: this subcomponent is wrapped by Form.create () (ElectricityTemp), which is the method provided by the From component in antdesign.
the following two components remove unnecessary code.
parent component: 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; **// atest?**
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;
subcomponent: 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;