Javascript 有没有办法为 React Native 设置 Picker 组件的样式并使其高度变小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39108283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:12:25  来源:igfitidea点击:

Is there a way to style Picker component for React Native and make its height smaller?

javascriptreact-nativestylespicker

提问by nbkhope

I wanted to use the Pickercomponent in my React Native application, but it takes up too much height of the screen. Is there a way to make the picker limit itself to show only, say, two items at a time, then be scrollable within?

我想在我的 React Native 应用程序中使用Picker组件,但它占用了太多的屏幕高度。有没有办法让选择器限制自己一次只显示两个项目,然后可以在其中滚动?

回答by Michael Cheng

From playing around with the styling, it looks like the most important part is to set the itemStyleprop and define the heightvalue there. You'll probably also want to style the Pickercomponent itself and set the heightvalue to be the same for the best looking results, but you don't needto do that.

从玩弄样式来看,看起来最重要的部分是设置itemStyle道具并在height那里定义值。您可能还希望Picker设置组件本身的样式并将height值设置为相同以获得最佳外观,但您不需要这样做。

About trying to show two rows:

关于尝试显示两行:

  • Showing one item looks to be around a height of 44.
  • You can't really show exactly two items in iOS because of how the native Picker component is designed. It'll show parts of what's above and below the currently selected value. So at best you can sort of show half/half of those values. You'll have to play around with the height to find something that works for you.
  • 显示一个项目看起来大约是 44 的高度。
  • 由于本机 Picker 组件的设计方式,您无法真正在 iOS 中准确显示两个项目。它将显示当前选定值上方和下方的部分。所以充其量你可以显示这些值的一半/一半。你必须玩弄高度才能找到适合你的东西。

Minimal Example:

最小示例:

<Picker style={{width: 200, height: 44}} itemStyle={{height: 44}}>
  <Picker.Item label="Java" value="java" />
  <Picker.Item label="JavaScript" value="js" />
</Picker>

Here's a Snackshowing a full example for varying heights (code copy pasted below):

这是一个小吃,展示了不同高度的完整示例(下面粘贴了代码副本):

import React, { Component } from 'react';
import { Text, View, StyleSheet, Picker } from 'react-native';

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      language: 'haxe',
      firstLanguage: 'java',
      secondLanguage: 'js',
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.title}>Unstyled:</Text>
        <Picker
          style={[styles.picker]} itemStyle={styles.pickerItem}
          selectedValue={this.state.language}
          onValueChange={(itemValue) => this.setState({language: itemValue})}
        >
          <Picker.Item label="Java" value="java" />
          <Picker.Item label="JavaScript" value="js" />
          <Picker.Item label="Python" value="python" />
          <Picker.Item label="Haxe" value="haxe" />
        </Picker>

        <Text style={styles.title}>Shows one row:</Text>
        <Picker
          style={[styles.onePicker]} itemStyle={styles.onePickerItem}
          selectedValue={this.state.firstLanguage}
          onValueChange={(itemValue) => this.setState({firstLanguage: itemValue})}
        >
          <Picker.Item label="Java" value="java" />
          <Picker.Item label="JavaScript" value="js" />
          <Picker.Item label="Python" value="python" />
          <Picker.Item label="Haxe" value="haxe" />
        </Picker>

        <Text style={styles.title}>Shows above and below values:</Text>
        <Picker
          style={[styles.twoPickers]} itemStyle={styles.twoPickerItems}
          selectedValue={this.state.secondLanguage}
          onValueChange={(itemValue) => this.setState({secondLanguage: itemValue})}
        >
          <Picker.Item label="Java" value="java" />
          <Picker.Item label="JavaScript" value="js" />
          <Picker.Item label="Python" value="python" />
          <Picker.Item label="Haxe" value="haxe" />
        </Picker>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    alignItems: 'center',
    padding: 20,
    backgroundColor: 'white',
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    marginTop: 20,
    marginBottom: 10,
  },
  picker: {
    width: 200,
    backgroundColor: '#FFF0E0',
    borderColor: 'black',
    borderWidth: 1,
  },
  pickerItem: {
    color: 'red'
  },
  onePicker: {
    width: 200,
    height: 44,
    backgroundColor: '#FFF0E0',
    borderColor: 'black',
    borderWidth: 1,
  },
  onePickerItem: {
    height: 44,
    color: 'red'
  },
  twoPickers: {
    width: 200,
    height: 88,
    backgroundColor: '#FFF0E0',
    borderColor: 'black',
    borderWidth: 1,
  },
  twoPickerItems: {
    height: 88,
    color: 'red'
  },
});

回答by Adrian Bartholomew

Set the Picker's itemStyleheight to the height of one: 44. Set its styleheight to 44. Remove flex: 1 if it exists.

PickeritemStyle高度设置为 1 的高度:44。将其style高度设置为 44。如果存在,则删除 flex: 1。

      <Picker
        selectedValue={this.state.selectedState}
        onValueChange={onValueChange}
        style={styles.picker}
        itemStyle={styles.pickerItem}
      >
        {this.state.states.map((v, i) => (
          <Picker.Item key={i} label={v.label} value={v.value} />
        ))}
      </Picker>


StyleSheet.create({
  picker: {
  // flex: 1,
    width: "100%",
    height: 44,
  },
  pickerItem: {
    height: 44
  }
})

回答by sachin Sharma

import React, { Component } from 'react';
import { View, ScrollView, TouchableOpacity, Text, StyleSheet } from "react-native";
import { Container, Content, Picker } from 'native-base';

export default class MyScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selected: "key1",
    };
  }
  onValueChange(value: string) {
    this.setState({
      selected: value
    });
  }

  render() {
    return (
      <View style={styles.mainContainer}>
        <View style={styles.pickerBoxContainer}>
              <View style={styles.pickerBoxInner}>
                <Picker
                  selectedValue={this.state.district}
                  style={styles.pickerStyle}
                  placeholder="Select your SIM"
                  onValueChange={(itemValue) =>
                    this.setState({ district: itemValue })
                  }>

                  <Picker.Item label="Wallet" value="key0" />
                  <Picker.Item label="ATM Card" value="key1" />
                  <Picker.Item label="Debit Card" value="key2" />
                  <Picker.Item label="Credit Card" value="key3" />
                  <Picker.Item label="Net Banking" value="key4" />
                </Picker>
                <Icon style={styles.pickerBoxIcon} name="arrow-drop-down" type="MaterialIcons" />
              </View>
            </View>
          </View>
      </View>
    );
  }
}


const styles = StyleSheet.create({
  mainContainer: {
    backgroundColor: BaseColors.white,
    flex: 1,
  },

 // picker box style
  pickerBoxContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    borderRadius: 8,
    marginTop: 10,
  },
  pickerBoxInner: {
    borderWidth: 0.6,
    borderColor: BaseColors.gray9,
    borderRadius: 2,
    overflow: 'hidden',
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
    height: 37,
  },
  pickerBoxIcon: {
    position: 'absolute',
    right: 0,
    fontSize: 23,
    color: BaseColors.gray7,
  },
  pickerStyle: {
    width: '120%',
    paddingBottom: 0,
    paddingLeft: 0,
    transform: [{ scaleX: 0.85 }, { scaleY: 0.85 }],
    left: -25,
    position: 'absolute',
    backgroundColor: 'transparent'
  }
});

回答by Norfeldt

What about this from NativeBase:

NativeBase 的情况如何:

import React, { Component } from 'react';
import { Container, Content, Picker } from 'native-base';
const Item = Picker.Item;?
export default class PickerExample extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedItem: undefined,
            selected1: 'key1',
            results: {
                items: []
            }
        }
    }
    onValueChange (value: string) {
        this.setState({
            selected1 : value
        });
    }
    render() {
        return (
            <Container>
                <Content>
                    <Picker
                        iosHeader="Select one"
                        mode="dropdown"
                        selectedValue={this.state.selected1}
                        onValueChange={this.onValueChange.bind(this)}>
                        <Item label="Wallet" value="key0" />
                        <Item label="ATM Card" value="key1" />
                        <Item label="Credit Card" value="key2" />
                        <Item label="Debit Card" value="key3" />
                   </Picker>
                </Content>
            </Container>
        );
    }
}

https://docs.nativebase.io/COMPONENTS.html#Picker

https://docs.nativebase.io/COMPONENTS.html#Picker