简体   繁体   中英

React-native - How to create a infinite picker

I would like to create a infinite/loop react-native Picker like on the image below.

在此处输入图片说明

So, my question is: When I'm scrolling, how can I make the Picker start again from the first item after reach out the last item?

Here's my code:

render() {
  const hourItems = [];
  for(var i = 0; i < 24; i++) {
    hourItems.push(
      <Picker.Item label={i.toString()} value={i} key={i} />
    );
  }

  return(
    <ScrollView style={styles.panel}>
      <Picker
        selectedValue={this.state.hour}
        onValueChange={(itemValue, itemIndex) => this.setState({ hour: itemValue })}
      >
        {hourItems}
      </Picker>
    </ScrollView>
  );
}

Create redux action which increment value of the minutes and hours. Inside that action you can check whether it should be reset, for example:

export const tick = () => (dispatch, getState) => {
   const { minute } = getState().clock
   if (minute === 59) {
     dispatch({ type: RESET_MINUTE})
     dispatch({ type: INCREMENT_HOUR})
   } else {
     dispatch({ type: INCREMENT_MINUTE})
   }
}

and in the reducer:

const createReducer = (initialState, handlers) =>
  (state = initialState, action) => {
    if (handlers.hasOwnProperty(action.type)) {
      return handlers[action.type](state, action)
    }
    return state
  }

export default createReducer(initialState, {
  INCREMENT_HOUR(state, action) {
    return {
      ...state,
      hour: state.hour + 1,
    }
  },
  INCREMENT_MINUTE(state, action) {
    return {
      ...state,
      minute: state.minute + 1,
    }
  },
  RESET_MINUTE(state) {
    return {
      ...state,
      minute: 0,
    }
  },
})

then connect your component with the reducer and the update should be automatic :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM