在React Native中,Refs、Memo化、HOC(高阶组件)和Context可以用来提高组件的性能和代码组织。以下是一些示例代码:
Refs:
import React, { useRef } from 'react';
import { TextInput } from 'react-native';
const App = () => {
const inputRef = useRef(null);
const focusTextInput = () => {
if (inputRef.current) {
inputRef.current.focus();
}
};
return (
<TextInput ref={inputRef} placeholder="点击按钮聚焦此输入框" />
<Button onPress={focusTextInput} title="聚焦输入框" />
);
};
Memo化组件:
import React, { memo } from 'react';
import { Text, View } from 'react-native';
const ExpensiveComponent = ({ text }) => (
<View>
<Text>{text}</Text>
</View>
);
export default memo(ExpensiveComponent, (prevProps, nextProps) => {
return prevProps.text === nextProps.text;
});
HOC高阶组件:
import React from 'react';
import { View } from 'react-native';
const withLogging = (WrappedComponent) => {
return (props) => {
console.log('Component is rendering');
return <WrappedComponent {...props} />;
};
};
const EnhancedComponent = withLogging(({ text }) => (
<View>
<Text>{text}</Text>
</View>
));
Context上下文:
import React, { useContext } from 'react';
import { Text, View } from 'react-native';
const ThemeContext = React.createContext({ color: 'black' });
const App = () => {
return (
<ThemeContext.Provider value={{ color: 'blue' }}>
<View>
<Text>主题颜色是{useContext(ThemeContext).color}</Text>
</View>
</ThemeContext.Provider>
);
};
这些代码示例展示了如何在React Native应用中使用Refs来直接操作子组件、如何使用memo
来防止不必要的组件更新、如何创建和使用HOC来在组件渲染前添加额外的行为、以及如何使用Context来共享应用范围内的数据。