【问题标题】:React Native - Margin in the intermediate elementsReact Native - 中间元素的边距
【发布时间】:2020-08-22 09:33:58
【问题描述】:

我想通过将样式添加到我的 App.js 文件来在标题和搜索栏之间添加空格。

Current Screenshot of my App

How I would like it to look

我尝试了以下方法,但没有成功

  • 不包括父视图中的styles.container。
  • 还有很多其他没有任何效果的小改动,也搜索了一下,没有发现与我的问题有关的内容。

App.js

import React from 'react';
import { View, StyleSheet, Text } from 'react-native';
import { Search } from './Components/Searchbar';
import { Listt } from './Components/List'

const App = () => {

  return (
    <View style={styles.container}>
      <Text style={styles.text}>My App</Text>
      <Search style={styles.search}/>
      <Listt style={styles.list}/>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    display: 'flex',
    alignItems: 'center',
  },
  text: {
    textAlign: 'center',
    color:'red',
    fontSize: 35,
    marginTop: 20,
  },
  search: {
    marginTop: 500,
  },
  list: {
    marginTop: 300,
  }
});

export default App;

搜索栏.js

import * as React from 'react';
import { Searchbar } from 'react-native-paper';

export class Search extends React.Component {
  state = {
    firstQuery: '',
  };

  render() {
    const { firstQuery } = this.state;
    return (
      <Searchbar
        placeholder="Search"
        onChangeText={query => { this.setState({ firstQuery: query }); }}
        value={firstQuery}
      />
    );
  }
}

【问题讨论】:

  • 您能否提供更多详细信息,例如您想要的预期输出?
  • 你能发布Search组件的代码吗?
  • 您的问题不够详细。你能画出预期的输出并在这里分享吗?

标签: react-native margin


【解决方案1】:

您可以通过多种方式获得所需的结果。 我假设您只是希望 Search 组件具有 marginTop: 500

这是一种常见的模式。然而,光靠它是不够的。

<Search style={styles.search}/>

原因是自定义组件默认不使用样式道具,除非它们是为此而构建的。

要让您的组件使用样式道具,您必须:

  1. 从该组件中访问所述样式
  2. 将其传递给原生组件(如 View)接受样式道具的组件。在你的情况下是后者。

这是一个接受样式属性的自定义组件示例。

export class Example extends React.Component {
  render() {
    const style = this.props.style;
    return (
      <View style={this.props}>
        <Text>Here is an example</Text>
      </View>
    );
  }
}

它是这样称呼的:

<Example style={styles.somestyle} />

根据 React Native Paper 的文档,Searchbar 组件接受一个样式属性。 https://callstack.github.io/react-native-paper/searchbar.html#style

这意味着您应该能够将样式传递给它,而无需将组件包装在 View 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多