【问题标题】:How to set default value for drop-down in react?如何在反应中设置下拉菜单的默认值?
【发布时间】:2019-04-23 06:07:34
【问题描述】:

您好,我正在研究 React Js 下拉菜单。我想在第一次呈现页面时为下拉菜单设置默认值。一旦用户从下拉列表中选择任何值,我就会在 redux 存储中存储相同的值并为下拉列表设置相同的值。下面是我的代码。

 render() {
  const {
   allOpenStoresSearchTerms,
    } = this.props;
    return (
     <SelectWithMargin
          instanceId="storeFilter"
          onChange={this.handleChange}
          value={allOpenStoresSearchTerms.selectedOption}
          options={options}
          placeholder="Store Type"
          clearable={false}
     />
  }
}

下面是我的句柄事件。

  handleChange(selectedOption) {
    this.props.searchParameters(
      this.state.searchValues,
      this.state.searchDbTarget,
      '',
      selectedOption
    );
    const openAllStores = {
      ...this.props.allOpenStoresSearchTerms,
      selectedOption,
    };
    this.props.setAllOpenStoresSearchTerms(openAllStores);
  }

每当我在下拉列表中选择某个值时,我都会将值存储在 redux 存储中并为下拉列表设置相同的值。现在我想在第一次加载页面时选择值。以下是下拉菜单的值。

 const options = [
  { value: 'true', label: 'Open Stores' },
  { value: 'false', label: 'All Stores' },
];

有人可以帮我在页面加载时设置默认值吗?我不确定我们需要在哪里设置默认值?任何帮助,将不胜感激。谢谢。

【问题讨论】:

  • 在redux中设置allOpenStoresSearchTerms.selectedOption默认值initialState ?
  • 可能我不知道。我想在页面加载时设置默认值 Open Stores。
  • 设置在你的initlaState{ allOpenStoresSearchTerms: { selectedOption: { value='true', label: 'Open Stores'} } }
  • 它正在工作。请发布答案。

标签: reactjs select


【解决方案1】:

设置默认值为initialState

const initialState = {
  allOpenStoresSearchTerms: {
    selectedOption: {
      value: 'true',
      label: 'Open Stores',
    },
  },
};

function reduer(state = initialState, action) {
  ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-29
    • 2018-09-29
    • 2013-11-09
    • 2018-02-08
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多