Javascript 将 Picker 绑定到 React Native 中的 Picker.Item 列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35397678/
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 17:40:49  来源:igfitidea点击:

Bind Picker to list of Picker.Item in React Native

javascriptreact-native

提问by Michael

I'm sure there is a way to do this, but I just can't see how yet.

我确信有一种方法可以做到这一点,但我还不知道如何做到。

What I'd like to do, is add a Picker component, but rather than hard-code the list of items, fetch this from a service and have the Picker bound to something I can populate later.

我想做的是添加一个 Picker 组件,而不是对项目列表进行硬编码,而是从服务中获取它并将 Picker 绑定到我以后可以填充的内容。

Here's what I have, but my app won't even run now. Any ideas please?

这是我所拥有的,但我的应用程序现在甚至无法运行。请问有什么想法吗?

'use strict';
var React = require('react-native');
var {
    Picker,
    Text,
    View
} = React;

var AvailableServices = React.createClass({
    getInitialState() {
        var fetchServicesUri = 'http://some.url/available_services';
        fetch(fetchServicesUri)
            .then((response) => response.json())
            .then((responseJson) => {
                console.log(responseJson);
                var services = [];
                for(var service in responseJson.services) {
                    services.push(<Picker.Item label={service.Label} value={service.Value}/>);
                }
                this.setState({
                    services: services
                });
            })
            .catch((error) => {
                console.warn(error);
            })
            .done();
        return {
            services: [],
            selectedService: null
        }
    },

    render() {
        return (
            <View>
                <Text>Pick a service</Text>
                <Picker
                    selectedValue={this.state.selectedService}
                    onValueChange={(service) => this.setState({selectedService:service})}
                >
                    {this.state.services}
                </Picker>
            </View>
        );
    }
});

module.exports = AvailableServices;

回答by Nader Dabit

You should probably set up your initial state as the empty array, then call your service on componentWillMount or componentDidMount. I've set up something that works with some dummy data here, and pasted the code below.

您可能应该将初始状态设置为空数组,然后在 componentWillMount 或 componentDidMount 上调用您的服务。我在这里设置了一些可以处理一些虚拟数据的东西,并粘贴了下面的代码。

'use strict';
var React = require('react-native');
var {
    Picker,
    Text,
    View,
      AppRegistry
} = React;

var PickerItem = Picker.Item;

var SampleApp = React.createClass({
    getInitialState() {
        return {
            services: ['a', 'b', 'c', 'd', 'e'],
            selectedService: 'a'
        }
    },

    componentDidMount() {
        setTimeout(() =>  { 
         this.setState({
          services: [ 'one', 'two', 'three', 'four', 'five' ]
         }) 
        }, 3000)
    },

    render() {
        let serviceItems = this.state.services.map( (s, i) => {
            return <Picker.Item key={i} value={s} label={s} />
        });

        return (
            <View>
                <Text>Pick a service</Text>
                <Picker
                    selectedValue={this.state.selectedService}
                    onValueChange={ (service) => ( this.setState({selectedService:service}) ) } >

                    {serviceItems}

                </Picker>
            </View>
        );
    }
});


AppRegistry.registerComponent('SampleApp', () => SampleApp);

回答by Abhishek Garg

No Loops required, here how i did in my react native based project, similar to above answer to bind or add data dynamically in Picker

不需要循环,这里我是如何在我的基于本机的项目中做的,类似于上面的答案来动态绑定或添加数据 Picker

import React, {Component} from 'react';
import {Picker,View} from 'react-native';
export default class SampleApp extends Component  {

    constructor(props){
        super(props);
        // HARD CODED DATA , YOU CAN REPLACE THIS DATA  WITH API CALL DATA IN ComponentDidMount() 
       //or in Constructor because countryData is not state.
        this.countryData = ["India","Pakistan","USA"];
        // STATE    
        this.state({
            selectedCountry : null
        });
    }
    // Our country list generator for picker
    countryList = () =>{
        return( this.countryData.map( (x,i) => { 
              return( <Picker.Item label={x} key={i} value={x}  />)} ));
    }
    // RENDER
    render() {
        return (
            <View>
                <Picker
                    selectedValue={this.state.selectedCountry}
                    onValueChange={ (value) => ( this.setState({selectedCountry : value}) )}>
                    { this.countryList() }
                </Picker>
            </View>
        );
    }
}

Hope you find my example simple to understand ;)

希望你觉得我的例子很容易理解;)

回答by Ilarion Halushka

IMPORTANT: if you try to iterate an array of numbers with mapthen don't forget that labelproperty of Picker.Itemshould be converted to string:

重要提示:如果您尝试使用数字数组进行迭代,map请不要忘记应将 的label属性Picker.Item转换为字符串

const pickerItems = [1,2,3].map(i => (
      <Picker.Item label={i.toString()} value={i} />
));

回答by Yash

You can try this one.

你可以试试这个。

<Picker
      selectedValue={this.state.facilityId}
      style={{ width: '100%' }}
      onValueChange={(itemValue) => this.setState({ facilityId: itemValue, facilityPicked: true })}>
      {facilities.map((facility, i) => {
        return <Picker.Item key={i} value={facility.id} label={facility.facility_name} />
      })}
</Picker>

Here, facilities is a list of object having id and facility_name as key.

这里,设施是一个以 id 和设施名称为键的对象列表。

回答by Rahul Kumar

I got the same error. The problem is not with picker but instead, with your code.

我得到了同样的错误。问题不在于选择器,而在于您的代码。

let items = props.category.map((item,index) => {
     return ( <Picker.Item key={index} label={item.category} value={item.category} /> )
   })
  return(
         <Picker style={styles.pickerStyle}>{items}</Picker>
        );

Instead of using item.category, i was using item.namewhich caused my app to stop. So check the value of your data.

item.category我没有使用item.name,而是使用它导致我的应用程序停止。因此,请检查您的数据的价值。

回答by Ritveak

Question:

题:

I am using map which is a data structure introduced in JS in ES6.

我使用的是地图,它是 ES6 中 JS 中引入的一种数据结构。

I am using Picker for the dropdown. here's my code :

我正在使用 Picker 作为下拉菜单。这是我的代码:

<Picker
            selectedValue={this.state.branch}
            style={styles.fieldPicker}
            mode="dropdown"

            onValueChange={(itemValue, itemIndex) =>
              this.setState({branch: itemValue})
            }>

            {/* Data Binding */}

                {this.state.branchData.forEach((name, id) => 
                      {
                      return <Picker.Item key={id} value={id} label={name} />;
                      })
                }



          </Picker>

I checked if name and id are being correctly accessed by logging it. The issue is that I am not able to see the dropdown getting populated.

我通过记录来检查名称和 ID 是否被正确访问。问题是我无法看到下拉列表被填充。