React Native 組件間通信方式詳解
在 React Native 開發中,組件間通信是核心概念之一。以下是幾種主要的組件通信方式及其適用場景:
- 簡單父子通信:使用 props 和回調函數
- 兄弟組件通信:提升狀態到共同父組件
- 跨多級組件:使用 Context API
- 全局狀態管理:Redux/MobX
- 完全解耦組件:事件總線
- 命令式操作:Refs
- 頁面間通信:路由參數
1. 父組件向子組件通信(Props 向下傳遞)
最基本的通信方式,通過 props 傳遞數據和回調函數。
// 父組件
function ParentComponent() {const [message, setMessage] = useState('Hello from Parent');return <ChildComponent greeting={message} />;
}// 子組件
function ChildComponent({greeting}) {return <Text>{greeting}</Text>;
}
特點:
- 單向數據流
- 簡單直接
- 適用于層級不深的組件結構
2. 子組件向父組件通信(回調函數)
通過 props 傳遞回調函數,子組件調用該函數與父組件通信。
// 父組件
function ParentComponent() {const handleChildEvent = (data) => {console.log('Data from child:', data);};return <ChildComponent onEvent={handleChildEvent} />;
}// 子組件
function ChildComponent({onEvent}) {return (<Button title="Send to Parent" onPress={() => onEvent('Child data')} />);
}
3. 兄弟組件通信(通過共同父組件)
function Parent() {const [sharedData, setSharedData] = useState('');return (<><SiblingA onUpdate={setSharedData} /><SiblingB data={sharedData} /></>);
}function SiblingA({onUpdate}) {return <Button title="Update" onPress={() => onUpdate('New data')} />;
}function SiblingB({data}) {return <Text>{data}</Text>;
}
4. Context API(跨層級通信)
適用于深層嵌套組件或全局狀態共享。
const MyContext = React.createContext();function App() {const [value, setValue] = useState('Default');return (<MyContext.Provider value={{value, setValue}}><ParentComponent /></MyContext.Provider>);
}function ChildComponent() {const {value, setValue} = useContext(MyContext);return (<Button title="Change Value" onPress={() => setValue('Updated')} />);
}
5. 事件總線(Event Emitter)
適用于完全解耦的組件通信。
// 創建事件總線
const EventBus = new NativeEventEmitter();// 發送端組件
function Publisher() {const emitEvent = () => {EventBus.emit('customEvent', {data: 'Event data'});};return <Button title="Emit Event" onPress={emitEvent} />;
}// 接收端組件
function Subscriber() {const [message, setMessage] = useState('');useEffect(() => {const subscription = EventBus.addListener('customEvent', (event) => {setMessage(event.data);});return () => subscription.remove();}, []);return <Text>{message}</Text>;
}
6. Redux 或 MobX(狀態管理庫)
適用于大型應用中的復雜狀態管理。
// Redux 示例
import { useSelector, useDispatch } from 'react-redux';function ComponentA() {const dispatch = useDispatch();const updateData = () => {dispatch({ type: 'UPDATE', payload: 'New data' });};return <Button title="Update Store" onPress={updateData} />;
}function ComponentB() {const data = useSelector(state => state.data);return <Text>{data}</Text>;
}
7. Refs(訪問組件實例)
用于命令式地訪問子組件。
function ParentComponent() {const childRef = useRef(null);const callChildMethod = () => {childRef.current.doSomething();};return (<><ChildComponent ref={childRef} /><Button title="Call Child Method" onPress={callChildMethod} /></>);
}// 需要使用 forwardRef
const ChildComponent = forwardRef((props, ref) => {useImperativeHandle(ref, () => ({doSomething: () => {console.log('Method called from parent');}}));return <Text>Child Component</Text>;
});
8. 路由參數(頁面間通信)
使用 React Navigation 等路由庫傳遞參數。
// 發送頁面
function HomeScreen({ navigation }) {return (<Buttontitle="Go to Details"onPress={() => navigation.navigate('Details', { itemId: 86 })}/>);
}// 接收頁面
function DetailsScreen({ route }) {const { itemId } = route.params;return <Text>Item ID: {itemId}</Text>;
}
選擇建議
- 簡單父子通信:使用 props 和回調函數
- 兄弟組件通信:提升狀態到共同父組件
- 跨多級組件:使用 Context API
- 全局狀態管理:Redux/MobX
- 完全解耦組件:事件總線
- 命令式操作:Refs
- 頁面間通信:路由參數
最佳實踐
- 優先考慮最簡單的 props 傳遞方式
- 避免過度使用 Context,合理劃分 Context 范圍
- 對于復雜應用,盡早引入狀態管理方案
- 謹慎使用 Refs,避免破壞 React 的數據流
- 事件總線適合完全解耦的非父子組件通信