一、React調用子組件方法不推薦
在React中,我們可以通過props將方法傳遞到子組件中,然後子組件通過調用該方法來觸發父組件的操作。但是在某些情況下,直接調用子組件方法可能會導致代碼結構不清晰、維護成本高等問題,因此React並不推薦我們使用該方式來調用子組件方法。
二、React調用兄弟組件方法
在React中,如果需要調用兄弟組件的方法,我們可以通過父組件將需要調用的方法傳遞給另一個子組件,從而實現兄弟組件之間的通信。代碼如下:
// ParentComponent.js
import React from 'react';
import ChildComponent1 from './ChildComponent1';
import ChildComponent2 from './ChildComponent2';class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.child1 = React.createRef();
this.child2 = React.createRef();
}handleButtonClick = () => {
this.child2.current.someMethod();
}render() {
return (
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/154944.html