简体   繁体   中英

<select> should have {defaultValue} or {value} instead of setting {selected}

I'm building an E-Commerce site with reactjs with styled-component. My page product.jsx that has the <select> element with different sizes of product [XS,S,M,L,XL] that causes error always shows this error upon render in console.dev:

Warning: Use the defaultValue or value props on instead of setting selected on .

I tried this code right below before but it doesn't work as expected. I'm expecting to show the first element as disabled and shouldn't be selected at all:

<Filter>
  <FilterTitle>Size</FilterTitle>
    <FilterSize onChange={(e) => setSize(e.target.value)}>
        {product.size?.map((s) => (
              <FilterSizeOption key={s}>{s}</FilterSizeOption>
        ))}
  </FilterSize>
</Filter>

Please help me fix this code below not the above one.

product.jsx code:

const FilterSize = styled.select`
  margin-left: 10px;
  padding: 5px;
  cursor: pointer;
  outline: 0px;
  font-size: inherit;
`;
const FilterSizeOption = styled.option``;

//...

<Filter>
    <FilterTitle>Size</FilterTitle>
    <FilterSize onChange={(e) => setSize(e.target.value)}>
         <FilterSizeOption selected={true} disabled="disabled">
              Choose a size:
         </FilterSizeOption>
         {product?.product?.size.map((s) => (
              <FilterSizeOption key={s} value={s}>
                   {s}
              </FilterSizeOption>
         ))}
    </FilterSize>
</Filter>

To resolve this error you need change value="default" instead of selected={true} , and on the FilterSize component should add defaultValue="default" . The defaultValue and value with the same value, you will bind the default selection. The default value you can rename yourself.

Before

在此处输入图像描述

After

在此处输入图像描述

const FilterSize = styled.select`
  margin-left: 10px;
  padding: 5px;
  cursor: pointer;
  outline: 0px;
  font-size: inherit;
`;
const FilterSizeOption = styled.option``;

const sizes = ['XS', 'S', 'M', 'L', 'XL'];

function App() {
  const [size, setSize] = useState();

  return (
    <>
      <FilterSize defaultValue="default" onChange={e => setSize(e.target.value)}>
        <FilterSizeOption value="default" disabled="disabled">
          Choose a size:
        </FilterSizeOption>
        {sizes.map(s => (
          <FilterSizeOption key={s} value={s}>
            {s}
          </FilterSizeOption>
        ))}
      </FilterSize>
    </>
  );
}

export default App;

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-2024 STACKOOM.COM