Components and Layout Source Code
Implementation of Core Components
View Component Core Implementation
// ReactNative/view/ViewManager.cpp
class ViewManager : public ViewManagerBase {
public:
ShadowNode * createShadow () const override {
return new ViewShadowNode (); // Create Corresponding Shadow Node
}
void updateProperties (
ShadowNode & node,
const folly::dynamic & props) override {
// Convert JS-Passed Properties to Native View Properties
auto viewProps = static_cast < ViewProps *> ( & node. getProps ());
if (props. count ( " backgroundColor " )) {
viewProps -> backgroundColor = parseColor (props[ " backgroundColor " ]);
}
// Other Property Handling...
}
};
Text Component Rendering Process
// ReactNative/text/TextShadowNode.js
class TextShadowNode extends ReactShadowNode {
measure ( layoutConstraints ) {
// 1. Calculate Text Layout
const { width, height } = measureText (
this .props.text,
this .props.style.fontSize,
this .props.style.fontFamily
);
// 2. Return Measurement Result
return { width, height };
}
}
Image Component Loading Mechanism
// ReactNative/image/ImageLoader.cpp
void ImageLoader:: loadImage (
const std::string & uri,
std:: function < void ( const ImageInfo & )> callback ) {
// 1. Check Memory Cache
if (memoryCache. has (uri)) {
callback (memoryCache. get (uri));
return ;
}
// 2. Asynchronous Network Request
httpClient. get (uri, [callback](const HttpResponse & response) {
// 3. Decode Image
ImageInfo imageInfo = decodeImage (response.body);
// 4. Update Cache
memoryCache.put(uri, imageInfo);
callback ( imageInfo );
});
}
Layout System Source Code Implementation
Flexbox Algorithm Core Logic
// ReactNative/layout/YogaNode.cpp
void YogaNode:: calculateLayout () {
// 1. Initialize Layout Parameters
initLayoutProps ();
// 2. Recursively Calculate Child Nodes
for (auto & child : children) {
child -> calculateLayout ();
}
// 3. Apply Flexbox Rules
applyFlexDirection ();
applyJustifyContent ();
applyAlignItems ();
// 4. Compute Final Layout
computeLayout ();
}
Layout Property Mapping Table
React Native Property Yoga Property Calculation Rule flexDirectionflexDirectionDetermines Main Axis Direction justifyContentjustifyContentMain Axis Alignment alignItemsalignItemsCross Axis Alignment flexWrapflexWrapWhether to Wrap
Stylesheet Source Code Implementation
StyleSheet.create Source Code
// ReactNative/StyleSheet/StyleSheet.js
function create ( styles ) {
const result = {};
for ( const key in styles) {
// 1. Validate Style Properties
validateStyle (key, styles[key]);
// 2. Convert Styles to Native Format
result[key] = processStyle (styles[key]);
// 3. Generate Unique ID for Style Sharing
styleRegistry. register (result[key]);
}
return result;
}
Style Merging Algorithm
// Style Merging Priority:
1. Inline Styles (Highest Priority)
2. StyleSheet Styles
3. Default Styles (Lowest Priority)
// Merging Implementation:
function mergeStyles ( ... styles ) {
return styles. reduce (( acc , style ) => {
return { ... acc, ... style }; // Shallow Merge
}, {});
}
// ReactNative/Platform/Platform.cpp
std::string Platform:: getOS () {
# if defined (__APPLE__)
return " ios " ;
#elif defined (__ANDROID__)
return " android " ;
# else
return " unknown " ;
#endif
}
bool Platform:: isTesting () {
return getEnvironmentVariable ( " REACT_NATIVE_TEST " ) == " 1 " ;
}
// File Naming Convention:
MyComponent.ios.js // iOS-Specific
MyComponent.android.js // Android-Specific
MyComponent.js // Shared Implementation
// Loading Logic:
function requireComponent ( name ) {
const platform = Platform. OS ;
const platformFile = ` ${ name } . ${ platform } .js` ;
try {
return require (platformFile); // Prefer Platform-Specific File
} catch (e) {
return require ( ` ${ name } .js` ); // Fallback to Shared File
}
}
Custom Component Source Code Implementation
Component Registration Mechanism
// Custom Component Export:
class MyComponent extends React . Component {
// Component Implementation
}
// Register Component:
MyComponent.viewConfig = {
uiViewClassName : ' MyComponent ' , // Native View Name
validAttributes : { // Supported Attributes
title : true ,
color : true
}
};
export default MyComponent;
Native Component Bridging
// Native View Manager:
class MyComponentManager : public ViewManager {
public :
ShadowNode * createShadow () const override {
return new MyComponentShadowNode ();
}
void updateProperties (
ShadowNode & node,
const folly::dynamic & props) override {
// Handle Custom Properties
if (props. count ( " customProp " )) {
auto shadow = static_cast < MyComponentShadowNode *> ( & node);
shadow -> setCustomProp (props[ " customProp " ]);
}
}
};
State Management Source Code
Context API Source Code Implementation
Context Creation and Consumption
// ReactNative/ReactContext/Context.js
function createContext ( defaultValue ) {
const context = {
_currentValue : defaultValue,
Provider : ({ value , children }) => {
// Update Current Value
context._currentValue = value;
return children;
},
Consumer : ({ children }) => {
// Read Current Value
return children (context._currentValue);
}
};
return context;
}
Context Propagation Mechanism
// Update Propagation Process:
1. Provider ' s value Change s
2. Triggers Subtree Re - rendering
3. Consumer Component Retrieves Latest Value via Closure
4. Executes Children Function to Re - render
// Performance Optimization:
- Use React.memo to Avoid Unnecessary Consumer Re - renders
- Split Multiple Contexts to Reduce Update Scope
Redux Source Code Implementation
Store Core Implementation
// ReactNative/Redux/store.js
function createStore ( reducer , initialState ) {
let state = initialState;
const listeners = [];
return {
getState () {
return state;
},
dispatch ( action ) {
// 1. Call Reducer to Calculate New State
state = reducer (state, action);
// 2. Notify All Subscribers
listeners. forEach ( listener => listener ());
},
subscribe ( listener ) {
listeners. push (listener);
return () => {
// Unsubscribe
listeners. splice (listeners. indexOf (listener), 1 );
};
}
};
}
Middleware Mechanism
// Middleware Execution Process:
dispatch = applyMiddleware (
middleware1,
middleware2
)(store.dispatch);
// Middleware Signature:
const loggerMiddleware = store => next => action => {
console. log ( ' dispatching ' , action);
const result = next (action); // Call Next Middleware
console. log ( ' next state ' , store. getState ());
return result;
};
MobX Source Code Implementation
Observer Pattern Implementation
// ReactNative/MobX/observable.js
function observable ( target ) {
const observers = new Set ();
return new Proxy (target, {
set ( obj , prop , value ) {
obj[prop] = value;
// Notify All Observers
observers. forEach ( observer => observer ());
return true ;
},
get ( obj , prop ) {
// Collect Dependencies
if (currentObserver) {
observers. add (currentObserver);
}
return obj[prop];
}
});
}
// Reaction Implementation:
function reaction ( track , effect ) {
let firstRun = true ;
currentObserver = effect;
track (); // Collect Dependencies
currentObserver = null ;
return autorun (() => {
if ( ! firstRun) {
effect ();
}
firstRun = false ;
});
}
Selective Rendering Optimization
// React.memo Implementation Principle:
function memo ( Component , arePropsEqual ) {
return function MemoizedComponent ( props ) {
// Use Shallow Comparison to Determine Re-rendering
const prevProps = useRef ();
if ( ! arePropsEqual (props, prevProps.current)) {
prevProps.current = props;
return < Component {... props } />;
}
return prevProps.current.child; // Reuse Last Render Result
};
}
State Update Batching
// Batch Update Implementation:
let updateQueue = [];
let isBatching = false ;
function batchedUpdates ( callback ) {
isBatching = true ;
callback ();
isBatching = false ;
flushUpdates (); // Execute All Updates in Queue
}
function enqueueUpdate ( update ) {
if (isBatching) {
updateQueue. push (update);
} else {
flushUpdate (update); // Execute Immediately
}
}
State Persistence Source Code Implementation
AsyncStorage Integration
// State Persistence Middleware:
function persistMiddleware ( store ) {
// Load Persisted State on Initialization
loadPersistedState (). then ( persistedState => {
store. dispatch ({ type : ' HYDRATE ' , payload : persistedState });
});
// Subscribe to State Changes
store. subscribe (() => {
const state = store. getState ();
savePersistedState (state);
});
}
// Asynchronous Storage Operations:
async function savePersistedState ( state ) {
try {
await AsyncStorage. setItem (
' @app_state ' ,
JSON . stringify (state)
);
} catch (e) {
console. error ( ' Failed to persist state ' , e);
}
}
Navigation and Routing Source Code
React Navigation Source Code Implementation
Navigator Core Architecture
// ReactNavigation/Navigator.js
function createNavigator ( ScreenComponents ) {
return {
Screen : ({ name , component }) => {
// Register Screen Component
ScreenComponents[name] = component;
},
Navigator : ({ initialRouteName , children }) => {
const [currentRoute, setCurrentRoute] = useState (initialRouteName);
return (
< View >
{ React.Children. map (children, child => {
if (child.props.name === currentRoute) {
return React. createElement (ScreenComponents[child.props.name]);
}
return null ;
}) }
</ View >
);
}
};
}
Stack Navigator Implementation
// Stack Navigation State Management:
function createStackNavigator () {
return {
state : {
index : 0 ,
routes : [{ key : ' Home ' , name : ' Home ' }]
},
actions : {
push ( routeName ) {
this .state.routes. push ({
key : generateKey (),
name : routeName
});
this .state.index = this .state.routes.length - 1 ;
},
pop () {
if ( this .state.index > 0 ) {
this .state.routes. pop ();
this .state.index -- ;
}
}
}
};
}
Navigation State Management Source Code Implementation
Navigation State Tree Structure
{
index: 1 , // Index of Currently Active Route
routes: [ // Route Stack
{ key : ' Home ' , name : ' Home ' }, // Initial Route
{
key : ' Details ' ,
name : ' Details ' ,
params : { id : 123 } // Route Parameters
}
]
}
State Persistence Implementation
// Navigation State Persistence:
function persistNavigationState ( navigation ) {
// Save State
const state = navigation. getState ();
AsyncStorage. setItem ( ' nav_state ' , JSON . stringify (state));
// Restore State
AsyncStorage. getItem ( ' nav_state ' ). then ( savedState => {
if (savedState) {
navigation. reset ({
... JSON . parse (savedState),
index : 0
});
}
});
}
Custom Navigation Bar Source Code Implementation
Navigation Bar Component Integration
// Custom Navigation Bar Implementation:
function CustomNavigationBar ({ navigation , scene }) {
const { options } = scene.descriptor;
return (
< View style ={ styles.navigationBar } >
< TouchableOpacity onPress ={ () => navigation. goBack () } >
< Text >Back</ Text >
</ TouchableOpacity >
< Text > { options.title } </ Text >
</ View >
);
}
// Register Navigation Bar:
Stack. Navigator ({
screenOptions : {
header : ( props ) => < CustomNavigationBar {... props } />
}
});
Navigation Parameter Passing
// Parameter Passing Mechanism:
navigation. navigate ( ' Details ' , {
itemId : 42 ,
otherParam : ' anything '
});
// Retrieve Parameters in Target Screen:
function DetailsScreen ({ route }) {
const { itemId, otherParam } = route.params;
// ...
}
Deep Linking Source Code Implementation
Deep Link Parsing Process
// Deep Link Handling:
function handleDeepLink ( link ) {
// 1. Parse URL
const { path, queryParams } = parseUrl (link);
// 2. Match Route Configuration
const route = matchRoute (path);
// 3. Navigate to Corresponding Screen
if (route) {
navigation. navigate (route.name, queryParams);
}
}
// Linking Configuration Example:
const linking = {
prefixes : [ ' myapp:// ' , ' https://myapp.com ' ],
config : {
screens : {
Home : ' home ' ,
Details : ' details/:id '
}
}
};
Route Guard Source Code Implementation
Permission Verification Middleware
// Navigation Guard Implementation:
function createProtectedNavigator ( Navigator ) {
return {
... Navigator,
navigate ( routeName , params ) {
if ( isProtectedRoute (routeName) && ! isLoggedIn ()) {
this . navigate ( ' Login ' );
return ;
}
Navigator. navigate (routeName, params);
}
};
}
// Usage Example:
const ProtectedStack = createProtectedNavigator (Stack.Navigator);
Route Interception Logic
// Route Interceptor:
function withNavigationGuard ( Component ) {
return function GuardedComponent ( props ) {
const navigation = useNavigation ();
useEffect (() => {
const unsubscribe = navigation. addListener ( ' beforeEach ' , ( to , from ) => {
if (to.meta.requiresAuth && ! isLoggedIn ()) {
return { redirect : ' Login ' };
}
});
return unsubscribe;
}, [navigation]);
return < Component {... props } />;
};
}