React-native - 如何创建无限选择器

时间:2017-08-12 22:23:50

标签: javascript react-native picker

我想创建一个无限/循环反应原生Picker,如下图所示。

enter image description here

所以,我的问题是: 当我滚动时,如何在伸出最后一个项目后从第一个项目再次启动Picker?

这是我的代码:

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>
  );
}

1 个答案:

答案 0 :(得分:0)

创建redux动作,增加分钟和小时的值。在该操作中,您可以检查是否应该重置,例如:

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})
   }
}

并在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,
    }
  },
})

然后将您的组件与reducer连接,更新应该是自动的:)