首页 > 解决方案 > 如何将购买选项移到右侧?

问题描述

我是 react-native 和移动应用程序的新手。我正在尝试构建一个基本的购物应用程序。我在左侧有物品,在右侧有购买选项,但“购买”选项位于物品列表下方

我尝试使用 AlignItems,justifyContent。

import React, { Component } from 'react';
import { Alert, Button, ScrollView, StyleSheet, AppRegistry, Text, View }
  from 'react-native';

const styles = StyleSheet.create({
  red: {
    color: 'red',
    fontWeight: 'bold',
    fontSize: 20,
  },
  buttonContainer: {
    margin: 0,
  },
  alternativeLayoutButtonContainer: {
    margin: 20,
    flexDirection: 'column',
    justifyContent: 'space-between'
  }
});




class Greeting extends Component {

  _onPressButton() {
    Alert.alert('Sorry you have no credit!')
  }

  render() {
    return (
      <View style={styles.alternativeLayoutButtonContainer}>
        <View style={{ alignItems: 'flex-start', height: 75 }}>
          <Text style={styles.red}>{this.props.name}</Text>

          <Button
            onPress={this._onPressButton}
            title="BUY"
          />
        </View>
      </View>


    );

  }
}

export default class LotsOfGreetings extends Component {



  render() {
    return (
      <ScrollView>
        <View style={{
          alignItems: 'flex-start', top: 0, flex: 2,
          backgroundColor: 'black'
        }}>

          <Greeting name='Shoe- 900' />
          <Greeting name='Football Studs - 700' />
          <Greeting name='Football - 600' />
          <Greeting name='Jersey - 450' />
          <Greeting name='Stockings - 200' />
          <Greeting name='Cones - 50' />
          <Greeting name='Whistle - 80' />
          <Greeting name='Shin Pads - 250' />
          <Greeting name='GoalKeeper gloves - 900' />
          <Greeting name='Nets - 1500' />

        </View>
      </ScrollView>
    );
  }
}

// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => LotsOfGreetings); 

我希望购买选项直接与项目列表对齐

标签: react-native

解决方案


您希望将文本和按钮放在一个 flex 容器中,负责定义它们的对齐方式。

您的问候组件:

class Greeting extends Component {

  _onPressButton() {
    Alert.alert('Sorry you have no credit!')
  }

  render() {
    return (
      <View style={styles.rowContainer}>
        <Text style={styles.text}>{this.props.name}</Text>
        <View style={styles.buttonContainer}>
          <Button
            onPress={this._onPressButton}
            title="BUY"
          />
        </View>
      </View>
    );

  }
}

现在的风格:

const styles = StyleSheet.create({
  rowContainer: {
    flex: 1,
    height: 75,
    width: '100%',
    flexDirection: 'row', // children will be on the same line
    justifyContent: 'space-between',
    alignItems: 'center',
    margin: 20,
  },
  buttonContainer: {
   flex: 1,
  },
  text: {
    flex: 2, // Text takes twice more space than button container
    color: 'red',
    fontWeight: 'bold',
    fontSize: 20,
  },
});

推荐阅读