首页 > 解决方案 > 样式不适用于 React Native 组件

问题描述

我正在用 React Native 创建我的第一个应用程序。从功能上讲,我的应用程序做了它应该做的事情,它显示了一些文本行,其中之一在按下它时会发生变化。问题是样式不适用 - 我没有收到任何错误,我导入了 StyleSheet。我在渲染方法中应用了我的样式;

//Header.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

export class Header extends React.Component {
    constructor(props) {
        super(props);
        this.state = {isLoggedIn: false};
    }
    toggleUser = ()=>{
        this.setState(previousState => {
            return { isLoggedIn: !previousState.isLoggedIn }
        });
    }

    render() {
        let display = this.state.isLoggedIn ? 'Sample User' : this.props.message ;
        return (
            <View style={styles.headStyle}>
                <Text 
                    style={styles.headText}
                    onPress={this.toggleUser}>{display}
                </Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    headText: {
        textAlign: 'right',
        color: '#ffffff',
        fontSize: 20
    },
    headStyle: {
        paddingTop: 30,
        paddingBottom: 10,
        paddingRight: 10,
        backgroundColor: '#35605a'
    }
});

然后,我在 Home.js 中导入 Header.js,如下图:

//Home.js

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Header } from '../Sections/Header.js';

export class Home extends React.Component {
    render() {
        return (
            <View>
                <Text>This is the homepage</Text>
                <Text>I've made several lines</Text>
                <Text>This is text shown in the app</Text>
                <Header message = 'Press to login' />
            </View>
        );
    }
}

最后我在 App.js 中显示 Home 类,如下所示;

//App.js

import React from 'react';
import { Home } from './App/Views/Home.js';

export default class App extends React.Component {
  render() {
    return (
      <Home />
    );
  }
}

我被困在这里,不知道错误可能出在哪里,如果需要任何其他信息,请告诉我,我很乐意提供。

标签: javascriptreactjsreact-native

解决方案


试试这样 import { TouchableOpacity } from 'react-native'

            <TouchableOpacity style={styles.headStyle}  onPress={this.toggleUser}>
                <Text 
                    style={styles.headText}
                    
                </Text>
            </TouchableOpacity>


推荐阅读