简体   繁体   English

如何设置在反应中选择的按钮默认值?

[英]How to set button default selected in react?

I've a react code (snippet, not a complete code) as shown below which shows list of timezones.我有一个react code (snippet, not a complete code) ,如下所示,它显示了时区列表。 On clicking a button, the timezone gets selected and it shows list of all programs.单击按钮时,时区被选中并显示所有程序的列表。

const timezones = [{label:"PT",timezone:"America/Los_Angeles"},{label:"NT",timezone:"America/St_Johns"}];

const Picker = (props) => {
    console.log(props.selectedTimezone);  // Line Z
    return(
       timezones.map((timezoneObject) => {
           console.log(timezoneObject.timezone);  // Line Y
          return <li><button className={`${timezoneObject.timezone === props.selectedTimezone ? 'selected' : ''}`}
             onClick={(e) => {
             e.preventDefault();
             props.onChange(timezoneObject.timezone);
          }}>{timezoneObject.label}</button></li>
       })
    )
}

What I want achieve is when the page loads then the timezone NT should remain automatically selected without clicking a button.我想要实现的是当页面加载时,时区NT应该保持自动选择,而无需单击按钮。 I've added console.log(props) at Line Z and I am getting NT on console but still the class selected is not getting applied for NT timezone .我已经console.log(props) at Line Z并且我在控制台上得到了NT但仍然class selected没有被应用于NT timezone Line Y prints : Line Y prints

America/Los_Angeles
America/St_Johns

React does not store state information between requests. React 不会在请求之间存储 state 信息。 Every time you refresh the page, the state refreshes as well.每次刷新页面时,state 也会刷新。 However, you can use LocalStorage to accomplish this.但是,您可以使用 LocalStorage 来完成此操作。

Here is a little snippet I found somewhere and adapted for one of the projects I'm working on:这是我在某处找到并适用于我正在从事的项目之一的小片段:

import { useEffect, useState } from 'react';

const useStickyState = (defaultValue, key) => {
  const [value, setValue] = useState(() => {
    const stickyValue = window.localStorage.getItem(key);
    return stickyValue !== null
      ? JSON.parse(stickyValue)
      : defaultValue;
  });

  useEffect(() => {
    window.localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

export default useStickyState;

Then in your component you can use it like this:然后在您的组件中,您可以像这样使用它:

...
import useStickyState from '../../app/useStickyState';
...

const YourComponent = () => {
  const [timeZone, setTimeZone] = useStickyState('NT', 'timezone');
  ...
}

The first parameter of useStickyState is the default value and the second parameter is the name of the LocalStorage key to be used. useStickyState的第一个参数是默认值,第二个参数是要使用的 LocalStorage 键的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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