鍍金池/ 問答/HTML/ 被antdesign中Form包裝后的子組件,通過refs獲取后無法調(diào)用其實例方

被antdesign中Form包裝后的子組件,通過refs獲取后無法調(diào)用其實例方法

react初學者,有個問題不清楚:
點擊按鈕,執(zhí)行this.calcAccount();

1.通過refs獲取到子組件,并調(diào)用其實例方法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}>結(jié)算</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;
回答
編輯回答
旖襯

對于你給的代碼:
不要將this定義為其他的東西,沒必須。jQuery的那套需要丟掉了。
this[`refs${i}`].test()
就可以了。
對于refs我想多寫點:
首先:在stateless組件中是無法使用refs的。
其實,在萬不得意的情況下盡量不要使用refs。
父組件調(diào)用子組件的方法是要獲取子組件的什么呢?
如果是數(shù)據(jù),那么父組件給子組件一個回調(diào)就可以了。
如果要執(zhí)行子組件的方法,那么可以將子組件包在父組件中,這樣通過高階組件實現(xiàn),例如:

const Parent = () => {};
const Children = ({children}) => {
    return (
        <Fragment>
         //子組件內(nèi)容
         {children}
        </Fragment>
    )
}

使用:

<Children>
    <Parent />
</Children>
2018年1月20日 02:25
編輯回答
六扇門

請問解決了嗎?我也遇到這個問題,父組件不能調(diào)用子組件form的方法

2018年8月12日 02:30
編輯回答
哎呦喂
name={`${_}${key}`}
2017年9月14日 15:25