首页 > 解决方案 > 如何在 React Native Expo 上使用多轮选择器

问题描述

我想使用像这个库这样的多轮选择器。

https://github.com/beefe/react-native-picker

但是,所有这些库都使用react-native link.

有什么解决办法吗?

标签: react-nativeexpopicker

解决方案


你对 react-native-picker 是正确的。它使用本机库,因此您不能将它与 expo.io 一起使用。

但是,您可以做的是创建一个函数(或模块或组件),给定一个数组数组,它​​将并排呈现选择器。这将创建一个多轮拾取器的效果。

这是这个想法的一个例子。

const Pickers = {
  /**
 * data: Array of Arrays. Each inner array will contains the values for each picker i.e: [[1,2,3],[:], [1,2,3,4]]
 * preselectedValue: Array with value for each column i.e: [2, :, 2]
 * confirmFunction: the function that you will do something with the alternated values in picker.
 */
  multiColumnPicker: (data, preselectedValue, confirmFunction) => {
    let _bindArray = preselectedValue;

    return (
      <View style={{
        flex: 1,
        flexDirection: 'row'
      }}>{/* Use FLEX to position columns side-by-side*/}

        {data.map((column, columnIndex) => {
          {/* Iterate data. For each inner array we create a <Picker> */}
          {/*note: indexOf works only with the same type of elements. So, ensure that the element you are looking for
            has the same type inside the array. In this example I wanted a String.*/}
          let _innerIndex = column.indexOf('' + _bindArray[columnIndex]);
          {/* Return the <Picker>. onValueChange we handle the changes accordingly and call the confirmation function. */}
          return <Picker
            key={columnIndex}
            selectedValue={column[_innerIndex]}
            style={{
            flex: 1
          }}
            onValueChange={(itemValue, itemIndex) => {
            _innerIndex = itemIndex;
            _bindArray[columnIndex] = itemValue;
            confirmFunction(_bindArray);
          }}>
            {/* Creates the list of options */}
            {column.map((item, idx) => <Picker.Item key={idx} label={item} value={item}/>)}
          </Picker>
        })}
      </View>
    )
  }
}

module.exports = Pickers;

然后在 render() 内的 View 组件中添加 {Pickers.multiColumnPicker:(data, preselectedValue, confirmFunction)}

希望它有所帮助:)


推荐阅读