Native Base Picker [React Native] 项目的条件渲染

Conditional Rendering on Items of Native Base Picker [React Native]

我正在为我们的产品使用“Native Base”组件,并且进展顺利, 但我被困在了一个点上,它是关于将 Items 放入 Nativebase Picker 中。我的代码是这样的

渲染方法代码 -

render(){

  return (

      <View style={{marginTop: 20,  flexDirection:'row', flexWrap:'wrap', justifyContent:'space-around', alignItems:'center'}}>

        <View style={{flex:1, justifyContent:'center', alignItems:'flex-end' }}>
          <Button
             style={{ backgroundColor: '#6FAF98', }}
             onPress={this._showDateTimePicker}

             >
             <Text>Select Date</Text>
          </Button>
        </View>

        <View style={{flex:1, justifyContent:'center', alignItems:'stretch'}}>
          <Picker
              style={{borderWidth: 1, borderColor: '#2ac', alignSelf:'stretch'}}
              supportedOrientations={['portrait','landscape']}
              iosHeader="Select one"
              mode="dropdown"
              selectedValue={this.state.leaveType}
              onValueChange={(value)=>this.setState({leaveType:value,})
                //this.onValueChange.bind(this)
              }>

              <Item label="Full Day" value="leave1" />
              {
                this.showStartDateFirstHalf() // Here I want to show this picker item on the basis of a condition 
              }
              <Item label="2nd half" value="leave3" />
         </Picker>
        </View>
        <DateTimePicker

          isVisible={this.state.isStartDatePickerPickerVisible}
          onConfirm={this._handleDatePicked}
          onCancel={this._hideDateTimePicker}
          mode='date'
        />

      </View>



    );


}

showStartDateFirstHalf()
{
    if(!this.state.isMultipleDays)
    {
      return(
          <Item label="1st Half" value="leave2" />
      );
    }
}

因此,如果 this.state.isMultipleDays 为假,此代码工作正常,但是当 this.state.isMultipleDays 为真时,这意味着当它位于 else 部分时,我收到此错误-

Cannot read property 'props' of undefined

我认为对此有一个更简单的答案。不要创建单独的 showStartDateFirstHalf() 函数,试试这个:

render() {

  const pickerItems = [
    {
      label: 'Full Day',
      value: 'leave1',
    },
    {
      label: '1st Half',
      value: 'leave2',
    },
    {
      label: '2nd Half',
      value: 'leave3',
    },
  ];

  const filteredItems = pickerItems.filter(item => {
    if (item.value === 'leave2' && this.state.isMultipleDays) {
      return false;
    }
    return true;
  });

  // The 'return' statement of your render function
  return (
    ...
    <Picker ...>
      {(() => 
        filteredItems.map(item => 
          <Item label={item.label} value={item.value} />
      )()}
    </Picker>
    ...
  );
}

这样,您就已经有了一个在渲染周期的 return 语句之前确定的项目列表。如果不满足条件,使用 filter 而不是 map 不仅会给你 null 作为第二个项目,而且会完全删除该项目。