programing

반응 선택 옵션을 스타일링하는 방법

fastcode 2023. 3. 16. 21:57
반응형

반응 선택 옵션을 스타일링하는 방법

a를 스타일링하는 가장 좋은 방법은?react-select컴포넌트(https://github.com/JedWatson/react-select) 옵션)

다음과 같은 방법으로 셀렉트 자체를 적절히 공략할 수 있습니다.

...
import Select from 'react-select'
...
const styles = {
  fontSize: 14,
  color: 'blue',
}
<Select
    options={[1,2,3,4]}
    placeholder={'Select something'}
    clearable={false}
    style={styles.select}
/>

문제는 선택을 확장할 때 실제 옵션이 기본값으로 유지된다는 것입니다.이러한 옵션을 어떻게 스타일링에 사용할 수 있습니까?

여기 내가 말하는 것의 예가 있다.플레이스 홀더의 스타일은 지정할 수 있지만 옵션은 지정할 수 없습니다.

react select v2(업데이트)

이 새로운 버전은 새로운 버전을 도입합니다.styles-api그 밖에 몇 가지 큰 변화가 있습니다.

커스텀 스타일

스타일 소품을 사용하여 커스텀 css를 사용하여 개별 컴포넌트를 스타일링합니다.

const colourStyles = {
  control: styles => ({ ...styles, backgroundColor: 'white' }),
  option: (styles, { data, isDisabled, isFocused, isSelected }) => {
    const color = chroma(data.color);
    return {
      ...styles,
      backgroundColor: isDisabled ? 'red' : blue,
      color: '#FFF',
      cursor: isDisabled ? 'not-allowed' : 'default',
      ...
    };
  },
  ...
};

export default () => (
  <Select
    defaultValue={items[0]}
    label="Single select"
    options={items}
    styles={colourStyles}
  />
);

이제 프로젝트 웹사이트에는 더 나은 문서와 더 명확한 예가 있습니다.

https://react-select.com/upgrade-guide#new-styles-api

https://react-select.com/home#custom-styles

https://react-select.com/styles#styles

react-select v1 (오래된 응답 - 권장되지 않음)

커스텀 클래스명

컴포넌트에 커스텀 className 프로펠을 제공할 수 있습니다.이 프로펠러는 base에 추가됩니다.외부 컨테이너의 className을 선택합니다.내장된 옵션렌더러는 커스텀 classNames도 지원합니다.

Add your custom className as a property to objects in the options array:
const options = [
    {label: "one", value: 1, className: 'custom-class'},
    {label: "two", value: 2, className: 'awesome-class'}
    // more options...
];
...
<Select options={options} />


메뉴렌더

menuRenderer 속성을 사용하여 기본 옵션 드롭다운 목록을 재정의할 수 있습니다.

option Class Name(옵션 클래스명)String옵션에 사용되는 className

예: react-select/master/src/utils/defaultMenuRenderer.js

@btzr의 답은 정확하고 스타일링은react-selectCSS 클래스를 사용하는 것은 (상대적으로) 간단합니다.

그러나 메뉴를 열고 항목을 검사하려고 할 때마다 메뉴가 다시 닫히기 때문에 메뉴 항목을 스타일링하는 것은 어렵습니다.

도움이 되는 것은 (일시적으로) 특정하는 것입니다.menuIsOpen={true}파라미터를 지정하면 메뉴가 열려 있어 검사가 용이해집니다.

btzr가 받아들인 답변은 맞으며, React에서 소품으로 전달되는 스타일로 요소를 스타일링해 봅시다.

저는 여전히 Sass 또는 Less를 사용하여 요소를 스타일링하는 것을 선호합니다. 왜냐하면 이러한 파일에는 요소가 많기 때문입니다.그래서 합격하는 거야classNamePrefix='filter'대신.

<Select
  classNamePrefix='filter'
  options={this.getOptions()}
  onChange={this.handleFilterChange}
  isMulti
  menuIsOpen
/>

그런 다음 해당 클래스 이름에 대해 Sass 또는 Less의 요소를 스타일링합니다.filter.

.filter {
  &__menu {
    margin: 0.125rem auto;
  }

  &__option {
    background-color: white;

    &--is-focused {
      background-color: lightblue;
    }
  }

  &__group {
    padding: 0;
  }

  &__menu-portal {
    border: 1px solid darkblue;
  }
}
const CustomStyle = {
  option: (base, state) => ({
    ...base,
    backgroundColor: state.isSelected ? {Color1} : {Color2},
  })
}
<Select styles={customStyle} >

여기에는 더 많은 옵션이 있습니다.스타일링에 대한 설명서를 참조하십시오.

https://react-select.com/styles

테마 스타일을 재정의하는 방법은 다음과 같습니다.

import React from "react";
import Select from "react-select";

class SelectComponent extends React.Component {
  componentDidMount() {}
  render() {
    const { data } = this.props;

    const options = [
      { value: "21", label: "21%" },
      { value: "9", label: "9%" },
      { value: "0", label: "0%" }
    ];

    const theme = theme => ({
      ...theme,
      colors: {
        ...theme.colors,
        primary25: "#f3f3f3",
        primary: "pink"

        // All possible overrides
        // primary: '#2684FF',
        // primary75: '#4C9AFF',
        // primary50: '#B2D4FF',
        // primary25: '#DEEBFF',

        // danger: '#DE350B',
        // dangerLight: '#FFBDAD',

        // neutral0: 'hsl(0, 0%, 100%)',
        // neutral5: 'hsl(0, 0%, 95%)',
        // neutral10: 'hsl(0, 0%, 90%)',
        // neutral20: 'hsl(0, 0%, 80%)',
        // neutral30: 'hsl(0, 0%, 70%)',
        // neutral40: 'hsl(0, 0%, 60%)',
        // neutral50: 'hsl(0, 0%, 50%)',
        // neutral60: 'hsl(0, 0%, 40%)',
        // neutral70: 'hsl(0, 0%, 30%)',
        // neutral80: 'hsl(0, 0%, 20%)',
        // neutral90: 'hsl(0, 0%, 10%)',
      }
      // Other options you can use
      // borderRadius: 4
      // baseUnit: 4,
      // controlHeight: 38
      // menuGutter: baseUnit * 2
    });

    return (
      <Select
        className="select"
        defaultValue={options[0]}
        options={options}
        theme={theme}
      />
    );
  }
}

export default SelectComponent;

스타일 사용:

const options = [
    {label: "one", value: 1, style: { color: 'red' }},
    {label: "two", value: 2, style: { color: 'blue' }}
    // more options...
];
...
<Select options={options} />

스타일링 리액션 셀렉트의 가장 좋은 방법은 아래와 같으며, 사람들은 또한 z-index에 대한 몇 가지 문제에 직면했습니다.

const colourStyles = {
  menuList: styles => ({
    ...styles,
    background: 'papayawhip',
  }),
  option: (styles, { isFocused, isSelected }) => ({
    ...styles,
    background: isFocused
      ? 'hsla(291, 64%, 42%, 0.5)'
      : isSelected
        ? 'hsla(291, 64%, 42%, 1)'
        : undefined,
    zIndex: 1,
  }),
  menu: base => ({
    ...base,
    zIndex: 100,
  }),
}

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
]

<Select
   // defaultValue={[colourOptions[2], colourOptions[3]]}
      name="colors"
      options={options}
      className="basic-multi-select"
      classNamePrefix="select"
      styles={colourStyles}
   />

다른 참가자와 마찬가지로, 데이터로부터 다른 옵션의 스타일을 어떻게 설정할지 혼란스러웠습니다.버전 1의 구문은 매우 심플한 것 같아서 3년 전 버전 사용을 검토했습니다!설명서의 예는 isDisabled, isFocused, 다중 콜백 등과 데이터의 스타일링을 조합하고 있기 때문에 이해하기 어렵습니다.

마침내 나는 드미트리 로고즈니의 CodeSandBox에서 쉬운 예를 발견했다.다음은 분기된 버전으로 React 기능 구문으로 업데이트되었으며 코드는 더욱 간략화되었습니다.https://codesandbox.io/s/react-select-css-styling-forked-mrspe

언급URL : https://stackoverflow.com/questions/45291508/how-to-style-react-select-options

반응형