开发者问题收集

react-native 中的 Picker 组件出现“Undefined 不是对象(评估‘child.props.value’)”错误

2017-10-04
5182

我在使用 Picker 组件时遇到了此错误,如下所示:

<Picker 
   style={{ flex: 1 }}>
   selectedValue={this.props.shift}
   onValueChange={value => this.props.employeeFormAction({ 
                                             prop:'shift', value })}
>   
        <Picker.Item label='Monday' value='Monday' />
        <Picker.Item label='Tuesday' value='Tuesday' />
        <Picker.Item label='Wednesday' value='Wednesday' />
        <Picker.Item label='Thursday' value='Thursday' />
        <Picker.Item label='Friday' value='Friday' />
        <Picker.Item label='Saturday' value='Saturday' />
        <Picker.Item label='Sunday' value='Sunday' />
</Picker> 

我已经尝试过来自同一社区的此解决方案

react-native - Picker - undefined 不是对象(评估'this.props.children[position].props)

但它对我不起作用。有人可以针对此问题提出解决方案吗?

2个回答

尽量不要对值进行硬编码。这种方式更简洁:

// inside your component (supposing is not a functional component)
_renderShifts = () => {
  const shifts = ['Monday', 'Tuesday', 'Wednesday','Thursday',
                'Friday','Saturday', 'Sunday'];

  return shifts.map((shift) => {
    <Picker.Item key={"shift_"+i} label={shift} value={shift} />
  });
}


// now your picker should render this way
_renderPicker = () => {
  <Picker 
    style={{ flex: 1 }}>
    selectedValue={this.props.shift}
    onValueChange={value => this.props.employeeFormAction({prop:'shift', value })}
  >   
    {this._renderShifts()}
  </Picker>
}
EnriqueDev
2017-10-04

当导入 Picker 时没有进行相应的对象解构,也会返回此错误。

不正确

import Picker from '@react-native-community/picker'

正确

import { Picker } from '@react-native-community/picker'
DariusLau
2020-10-24