likes
comments
collection
share

react与ReactNative的比较

作者站长头像
站长
· 阅读数 6

接触了react和reactNative,想简单比较一下这两者之间的关联和区别。。。待补充。。。

1、css样式使用

(1)动态更新

<View style={[styles.container, i==0 && styles.dynamicStyle]}>  
    <Text>Hello React Native!</Text>  
</View>

react native采用StyleSheet.create方法创建一个样式表对象,在使用的时候是通过组件的style属性传递样式表中的样式,这种方式可以直接进行动态调整样式。我们甚至可以在StyleSheet.create外层包装一层函数,通过传递属性的方式获取不同的样式,总之,通过一个方法来获取样式灵活性是非常高的!

// 包装一个动态样式方法
import { StyleSheet } from 'react-native';
import { themeProvider } from './themeProvider';

export function DynamicStyleSheet(callback) {
    const cache = {
        light: undefined,
        dark: undefined,
    };
    return (theme) => {
        const currentTheme = theme || themeProvider.theme;
        let style = cache[currentTheme];
        if (!style) {
            style = StyleSheet.create(callback(currentTheme));
            cache[currentTheme] = style;
        }
        return style;
    };
}
// 样式中的颜色需要currentTheme属性来获取不同的颜色。
const dynamicStyels = DynamicStyleSheet((theme) => {
    container: {
        backgroundColor: Color.black(theme)}
    }
);
// 使用
<View style={dynamicStyels(theme).container}/>

react通常引入.css样式文件,并使用className等选择器进行匹配,分离样式和内容。比如:

<div className="container">  
    <p>Hello React!</p>  
</div>
// .css文件
.container {
    margin-left: 16px;
}

当然react也可以使用内联的方式,也可以进行动态设置:

<div style={{backgroundColor: 'red'}}>  
    <p>Hello React!</p>
</div>

css动态改变样式通常就是要不更换选择器,要不使用内联的方式,但是要整个页面都动态设置样式就不太合适了(目前只了解到这个程度)!CSS选择器的优点是分离样式和内容、可重用性和统一管理,缺点是全局作用域和难以动态修改;内联样式的优点是动态修改,缺点是代码冗余难以维护,而且内联样式的优先级较高,很难通过其他样式规则来覆盖内联样式。

(2)用法多样性和区别

一,css不仅有多种选择器(类选择器、id选择器、属性选择器和关系选择器),还有伪类、伪元素,一方面丰富了一些react native上不常用的一些样式比如focus等,另一方面减少了一些类的定义。

二,react native封装了许多组件,组件会提供onLayout等方法,在组件加载后触发,这样便于进行动态更新。而且不同组件会有不同的方法,来实现布局相关操作。而react则是基于html元素的,通常只用useEffect,使用useEffect需要把握住好触发时机,但是react有一个优势是可以使用document提供的方法document.querySelectorAll可以一次性获取到整个列表。比如:

const Main = () => {
    useEffect(() => {
        const buttons = document.querySelectorAll('.operation-button');
        // 通过遍历找出最宽的标题宽度
        let currentTitleMaxWidth = 0;
        buttons.forEach((button) => {
            const width = button.getBoundingClientRect().width;
            if (width > currentTitleMaxWidth) {
                currentTitleMaxWidth = width;
            }
        });
        buttons.forEach((button) => {
            (button as HTMLElement).style.width = `${currentTitleMaxWidth}px`;
        });
    }, [])
    
    return (
        <div>
            {operationList.map((operation, index) => {
                return (
                    <div className="operation-button">{operation.title}</div>
                )
            })}
        </div>
    );
}

(有待进一步学习)

转载自:https://juejin.cn/post/7361056871673249829
评论
请登录