Передача данных в пользовательский сборщик - PullRequest
0 голосов
/ 06 ноября 2019

В настоящее время я занимаюсь разработкой приложения с помощью средства выбора и использую компонент средства выбора от собственного реагирования, но он не работает идеально на устройстве iOS, поэтому я нашел пользовательское средство выбора, использующее средство выбора, и его модальное отображение модальное натолько для iOSВот код

class PickerWrapper extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            type_absen: '',
            modal: false,
        }
    }

    render() {
        let picker;

        let iosPickerModal = (
            <Modal isVisible={this.state.modal} hideModalContentWhileAnimating={true} backdropColor={color.white} backdropOpacity={0.9} animationIn="zoomInDown" animationOut="zoomOutUp" animationInTiming={200} animationOutTiming={200} onBackButtonPress={() => this.setState({ modal: false })} onBackdropPress={() => this.setState({ modal: false })} >
                <View style={{ backgroundColor: color.white, width: 0.9 * windowWidth(), height: 0.3 * windowHeight(), justifyContent: 'center' }}>
                    <Picker
                        selectedValue={this.state.type_absen}
                        onValueChange={(itemValue, itemIndex) => {
                            this.setState({ type_absen: itemValue });
                            this.setState({ modal: false });
                            setTimeout(() => this.props.onSelect(itemValue), 1200);
                        }}
                    >
                        {this.props.items.map((item, key) => <Picker.Item label={item} value={item} key={key} />)}
                    </Picker>
                </View>
            </Modal>);

        if (Platform.OS === 'ios')
            return (
                <View style={this.props.style}>
                    {iosPickerModal}
                    <TouchableOpacity onPress={() => this.setState({ modal: true })}>
                        <View style={{ flexDirection: 'row', height: this.props.height ? this.props.height : normalize(40), width: this.props.width ? this.props.width : 0.68 * windowWidth(), borderWidth: 1, borderColor: color.blue, alignItems: 'center', borderRadius: 5 }}>
                            <Text style={{ fontSize: fontSize.regular, marginRight: 30 }}> {this.state.type_absen}</Text>
                            <IconWrapper name='md-arrow-dropdown' type='ionicon' color={color.light_grey} size={20} onPress={() => this.setState({ modal: true })} style={{ position: 'absolute', right: 10 }} />
                        </View>
                    </TouchableOpacity>
                </View >);
        else
            return (
                <View style={this.props.style} >
                    <Picker
                        selectedValue={this.state.type_absen}
                        style={{ height: this.props.height ? this.props.height : normalize(20), width: this.props.width ? this.props.width : normalize(150) }}
                        onValueChange={(itemValue, itemIndex) => {
                            this.setState({ type_absen: itemValue });
                            this.props.onSelect(itemValue);
                        }}
                    >
                        {this.props.items.map((item, key) => <Picker.Item label={item} value={item} key={key} />)}
                    </Picker>
                </View>);
    }
}

PickerWrapper.propTypes = {
    onSelect: PropTypes.func.isRequired
}

export default PickerWrapper;

Я успешно загрузил данные из API, но я все еще не понял, как получить значение из него, и вот мой старый код с использованием компонента выбора

<Picker
 selectedValue={this.state.type_absen}
 style={{backgroundColor:'white'}}
 onValueChange={(val) => this.setState({ type_absen: val })}> 
   {
   this.props.schedules ?   this.props.schedules.map((item, key) => { 
     return <Picker.Item value={item.id} label {item.description} key={item.id} />})
 :
  []
   } 
</Picker>

и это мой новый код с использованием PickerWrapper

export const mapStateToProps = state => ({
  token: state.authReducer.token,
  message: state.authReducer.message,
  schedules: state.authReducer.schedules
});

export const mapDispatchToProps = (dispatch) => ({
  actionsAuth: bindActionCreators(authAction, dispatch)
});

class Change extends Component {
    
  constructor(){
        super();
        this.state={
            type_absen: [],
        }
    }
    
    onPickerValueChange=(value, index)=>{
    this.setState({type_absen: value}, 
      () => {
        Alert.alert("type_absen", this.state.type_absen);
      }
    );
  }
  
  render() {
      return (
        <View style={styles.container}>
              <View style={styles.container}>
                <View style={styles.innerContainer}>             
                  <PickerWrapper items={this.props.schedules.map((item) => item.description )} onSelect={this.onPickerValueChange} />
                  
                </View>  
              </View>
        </View>
      );
  }
}
    
 }

Я пытаюсь получить item.id. Как мне это сделать в моем компоненте PickerWrapper?

1 Ответ

1 голос
/ 06 ноября 2019

В компоненте класса измените упаковщик средства выбора следующим образом

export const mapStateToProps = state => ({
    token: state.authReducer.token,
    message: state.authReducer.message,
    schedules: state.authReducer.schedules
  });

  export const mapDispatchToProps = (dispatch) => ({
    actionsAuth: bindActionCreators(authAction, dispatch)
  });

  class Change extends Component {

    constructor(){
          super();
          this.state={
              type_absen: [],
          }
      }

      onPickerValueChange=(value, index)=>{
      this.setState({type_absen: value}, 
        () => {
          Alert.alert("type_absen", this.state.type_absen);
        }
      );
    }

    render() {
        return (
          <View style={styles.container}>
                <View style={styles.container}>
                  <View style={styles.innerContainer}>             
                    <PickerWrapper items={this.props.schedules} onSelect={this.onPickerValueChange.bind(this)} />

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

, а затем в своем компоненте PickerWrapper измените его следующим образом


class PickerWrapper extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            type_absen: '',
            modal: false,
        }
    }

    render() {
        let picker;

        let iosPickerModal = (
            <Modal isVisible={this.state.modal} hideModalContentWhileAnimating={true} backdropColor={color.white} backdropOpacity={0.9} animationIn="zoomInDown" animationOut="zoomOutUp" animationInTiming={200} animationOutTiming={200} onBackButtonPress={() => this.setState({ modal: false })} onBackdropPress={() => this.setState({ modal: false })} >
                <View style={{ backgroundColor: color.white, width: 0.9 * windowWidth(), height: 0.3 * windowHeight(), justifyContent: 'center' }}>
                    <Picker
                        selectedValue={this.state.type_absen}
                        onValueChange={(itemValue, itemIndex) => {
                            this.setState({ type_absen: itemValue });
                            this.setState({ modal: false });
                            setTimeout(() => this.props.onSelect(itemValue), 1200);
                        }}
                    >
                        {this.props.items.map((item, key) => <Picker.Item label={item.description} value={item.id} key={key} />)}
                    </Picker>
                </View>
            </Modal>);

        if (Platform.OS === 'ios')
            return (
                <View style={this.props.style}>
                    {iosPickerModal}
                    <TouchableOpacity onPress={() => this.setState({ modal: true })}>
                        <View style={{ flexDirection: 'row', height: this.props.height ? this.props.height : normalize(40), width: this.props.width ? this.props.width : 0.68 * windowWidth(), borderWidth: 1, borderColor: color.blue, alignItems: 'center', borderRadius: 5 }}>
                            <Text style={{ fontSize: fontSize.regular, marginRight: 30 }}> {this.state.type_absen}</Text>
                            <IconWrapper name='md-arrow-dropdown' type='ionicon' color={color.light_grey} size={20} onPress={() => this.setState({ modal: true })} style={{ position: 'absolute', right: 10 }} />
                        </View>
                    </TouchableOpacity>
                </View >);
        else
            return (
                <View style={this.props.style} >
                    <Picker
                        selectedValue={this.state.type_absen}
                        style={{ height: this.props.height ? this.props.height : normalize(20), width: this.props.width ? this.props.width : normalize(150) }}
                        onValueChange={(itemValue, itemIndex) => {
                            this.setState({ type_absen: itemValue });
                            this.props.onSelect(itemValue, index);
                        }}
                    >
                        {this.props.items.map((item, key) => <Picker.Item label={item.description} value={item.id} key={key} />)}
                    </Picker>
                </View>);
    }
}

PickerWrapper.propTypes = {
    onSelect: PropTypes.func.isRequired
}

export default PickerWrapper;
...