【问题标题】:How can i pass the props to change the width of react-select component我如何通过道具来改变 react-select 组件的宽度
【发布时间】:2019-11-10 18:55:53
【问题描述】:

这就是我调用组件的方式,我在这里传递道具并想使用它但不知道在代码中使用这些道具。

<Selector
  key={index}
  placeholder={"Select an option."}
  defaultMenuIsOpen={true}
  isSearchable={false}
  options={options}
  width={"600px"} //this is the props i want to use for width
  color={"red"} // this props I want to use for color
  onChange={(e: string | any) => {
    const { value } = e;
    this.handleCondition(value, index, "condition");
  }}
/>

这是 react-select 的样式部分,我想在这里使用道具

export const customStyles: StylesConfig = {
    indicatorSeparator: () => ({ display: 'none' }),
    menu: () => ({
        width: '250px',
        marginTop: '4px',
        border: 'solid 1px #dfe3e9',
        borderRadius: '4px!important',
        boxShadow: '0 0 8px 0 #e5e5ea',
        position: 'absolute',
        zIndex: 999999,
        backgroundColor: 'white',
    }),
    control: (props) => ({
        display: 'flex',
        // width: props.width ? `${props.width}` : '250px',
        width: props.width ? props.width : '250px',
        height: '49px!important',
        borderRadius: '4px!important',
        border: 'solid 1px #dfe3e9',
        color: '#1e58c9',
    }),
    singleValue: () => ({
        color: '#1e58c9',
        flexWrap: 'nowrap'
    })

}

这是 React 部分,这是我正在渲染的内容

<ReactSelect
  options={this.props.options}
  styles={customStyles}
  {...this.props}
/>
{allowClosing && (
  <CloseWidget place={dpdown} allowClosing={allowClosing} id={id} />
)}

【问题讨论】:

    标签: reactjs react-select


    【解决方案1】:

    你可以例如将该配置对象保留为类变量,以访问道具和状态:

    state = {
       width: 250,
    }
    
    customStyles: StylesConfig = {
       indicatorSeparator: () => ({ display: 'none' }),
       menu: () => ({
          width: this.state.width + 'px',
       }),
    }
    

    您还必须检查道具是否已更改:

    static getDerivedStateFromProps(props, state) {
      if (state.width !== props.width)
         return {
            width: props.width,
         };
      }
    }; 
    

    然后在你的组件中:

    <ReactSelect
       options={this.props.options}
       styles={this.customStyles}
       {...this.props}
    />
    

    【讨论】:

    • 谢谢您,更改“customStyles”位置帮助我。现在我已经在一个类中声明了它,所以它就像一个魅力谢谢。
    • 而且在我更改customStyle的位置后,我可以直接使用道具我不再需要使用状态了。
    • @AmeyZulkanthiwar 很高兴听到:))
    猜你喜欢
    • 2016-12-10
    • 2021-11-24
    • 2022-11-14
    • 2021-05-21
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多