【问题标题】:Having problem using Stylesheet.create in react native在 react native 中使用 Stylesheet.create 时遇到问题
【发布时间】:2020-09-02 20:03:13
【问题描述】:

我是新来的反应原生并且在元素样式方面遇到问题。我按照告诉使用 StyleSheet.create() 方法的文章并尝试设置我的元素的样式,但我收到错误

style 属性需要从样式属性到值的映射,而不是字符串。例如,使用 JSX 时 style={{marginRight: spacing + 'em'}}。 这是我的参考代码

MyComponent.js

import React from 'react';
import { Icon } from 'react-native-material-ui';
import { StyleSheet, Text, View } from 'react-native';
import {header} from '../assets/css/style.js'

export default class MyComponent extends React.Component {
    state = {

    }
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div style={ styles.headerStyle }>
              <h2 style={ styles.headerMargin }> Hello! </h2>
            </div>
   }
const styles = StyleSheet.create({
    headerStyle : header.headerStyle,
    headerMargin:header.headerMargin
});

style.js

export const header= {
    headerStyle: {
        backgroundColor: '#000',
        paddingTop: '20px',
        paddingBottom: '20px',
        color: '#fff'
    },
    headerCenter: {
        width: '100%',
        textAlign: 'center',
        display: 'block'
    },
    headerMargin: {
        margin: '0',
        padding: '0'
    }
}


【问题讨论】:

  • 在 React Native 中,您可以使用(视图和文本)代替(div 和 h2)。你能解决这个问题吗?

标签: javascript css react-native


【解决方案1】:

在 react native 中,您需要使用整数值设置维度。因为 RN 会使用 DP 设置维度,而不是像素。

所以,0 不能是“0”。要设置paddingTop 20dp,您需要设置paddingTop: 20(无像素)。

在您的代码中,您将 0 设置为字符串 (styles.js)。这将引发错误。

使用这个固定的style.js 代码:

styles.js

export const header= {
    headerStyle: {
        backgroundColor: '#000',
        paddingTop: 20,
        paddingBottom: 20,
        color: '#fff'
    },
    headerCenter: {
        width: '100%',
        textAlign: 'center',
        display: 'block'
    },
    headerMargin: {
        margin: 0,
        padding: 0
    }
}

【讨论】:

    猜你喜欢
    • 2021-09-11
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    相关资源
    最近更新 更多