【问题标题】:Change selected value component in react-select更改反应选择中的选定值组件
【发布时间】:2019-07-31 05:45:09
【问题描述】:

有什么方法可以更改选定的值组件设计,在我的选项菜单中,我显示 CscId 和 CscDesc 但是当我选择选项时,我只想显示 CscId。有什么方法可以更改选定的值组件?我用谷歌搜索这个,已经花了 1 天。请帮帮我。

这是我的反应选择

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

const costcenterselect = ({ value, onChange, id, datasource }) => {    
  const formatOptionLabel = ({ CscID, CscDesc }) => (            
    <div style={{ display: "flex"}}>
      <div style={{width:'40%'}}>{CscID}</div>                
      <div>{CscDesc}</div>                
    </div>
  );  

  return (
    <div>
      <Select 
        id={id}
        menuIsOpen={true}    
        formatOptionLabel={formatOptionLabel}
        getOptionValue={option => `${option.CscID}`}
        options={datasource}
        onChange={onChange}
        defaultValue={value}        
      />
    </div>           
  )
}

export default costcenterselect;

【问题讨论】:

    标签: reactjs react-select


    【解决方案1】:

    您可以使用formatOptionLabel 本身来完成。它有第二个参数,为您提供元信息,如context,您可以使用它来有条件地渲染。这是working demo

    您可以看到context === value 允许您为选定的值进行渲染,而context === menu 为选项进行渲染。

    const formatOptionLabel = ({ CscID, CscDesc }, { context }) => {
        if (context === "value") {
          return <div>{CscID}</div>;
        } else if (context === "menu") {
          return (
            <div style={{ display: "flex" }}>
              <div style={{ width: "40%" }}>{CscID}</div>
              <div>{CscDesc}</div>
            </div>
          );
        }
      };
    

    【讨论】:

    • 天啊,非常感谢,正是我想要的。请问你是怎么知道这个功能的?
    • 很高兴它有帮助。也许从react-select 的文档中不容易访问它,但仔细观察你会发现formatOptionLabel 函数的整个定义是given there。另外,由于它是开源的,你也可以在github issues 找到解决方案。
    猜你喜欢
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 2012-01-29
    • 2019-05-25
    相关资源
    最近更新 更多