Как вертикально центрировать элемент в React native - PullRequest
0 голосов
/ 02 апреля 2020

Отказ от ответственности: Это вопрос к школьному проекту.

Я работаю над проектом с полным стеком, который использует React Native для внешнего интерфейса. У меня возникли проблемы с макетом страницы. Вот мой код:

Приложение. js:

import React, {useState} from 'react';
import { StyleSheet, Text, View, Switch } from 'react-native';

import Header from "./components/Header";

export default function App() {
  const [isEnabled, setIsEnabled] = useState(false);
  const toggleSwitch = () => setIsEnabled(previousState => !previousState);
  return (
    <View style={styles.screen}>
      <Header title="Web Application" />
      <Text style={styles.text}>Example Text</Text>
      <Text style={styles.text}>Not much here yet, so play with this switch</Text>
      <Switch
        style={styles.switch}
        trackColor={{ false: "#767577", true: "#81b0ff" }}
        thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
        ios_backgroundColor="#3e3e3e"
        onValueChange={toggleSwitch}
        value={isEnabled}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  screen: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  text: {
    flex: 1,
    textAlign: 'center',
    fontWeight: 'bold',
    fontSize: 24,
    backgroundColor: 'white'
  },
  switch: {
    alignSelf: 'center',
    flexDirection: 'column',
    justifyContent: 'space-between'
  }
});
Заголовок. js

import React from "react";
import { StyleSheet, View, Text, Platform } from "react-native";

import Colors from "../constants/colors";

const Header = props => {
  return (
    <View style={{ ...styles.headerBase, ...Platform.select({ios: styles.headerIOS, android: styles.headerAndroid, web: styles.headerBase})}} >
      <Text style={styles.headerTitle}>{props.title}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  headerBase: {
    width: "100%",
    height: 90,
    paddingTop: 36,
    alignItems: "center",
    justifyContent: "center",

  },
  headerIOS: {
    backgroundColor: 'black',
    borderBottomColor: '#ccc',
    borderBottomWidth: 1,
  },
  headerAndroid: {
    backgroundColor: Colors.primary,
  },
  headerTitle: {
    color: Platform.OS === 'ios' ? Colors.primary : 'black',
    fontSize: 24
  },
});

export default Header;

То, что я пытаюсь сделать с ними, это иметь верхний колонтитул, затем текст, а затем, по центру (по вертикали и горизонтали), я хотел бы иметь переключатель. Вместо этого этот код в настоящее время правильно размещает заголовок и текст, но переключатель находится в самом низу. Любая помощь / ресурсы будут оценены.

1 Ответ

1 голос
/ 02 апреля 2020

Попробуйте без flex: 1 для стиля текста.

import React, {useState} from 'react';
import { StyleSheet, Text, View, Switch } from 'react-native';

import Header from "./components/Header";

export default function App() {
  const [isEnabled, setIsEnabled] = useState(false);
  const toggleSwitch = () => setIsEnabled(previousState => !previousState);
  return (
    <View style={styles.screen}>
      <Header title="Web Application" />
      <Text style={styles.text}>Example Text</Text>
      <Text style={styles.text}>Not much here yet, so play with this switch</Text>
      <Switch
        style={styles.switch}
        trackColor={{ false: "#767577", true: "#81b0ff" }}
        thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
        ios_backgroundColor="#3e3e3e"
        onValueChange={toggleSwitch}
        value={isEnabled}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  screen: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  text: {
    textAlign: 'center',
    fontWeight: 'bold',
    fontSize: 24,
    backgroundColor: 'white'
  },
  switch: {
    alignSelf: 'center',
    flexDirection: 'column',
    justifyContent: 'space-between'
  }
});

Вот документация .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...