[英]React-Select - Replacing Components for custom option content
使用 React-Select(版本 2),我想要自定義設計(選擇)選項。
該文檔表明,替換組件將是我可以用來實現這一目標的一種方法。
不幸的是,我無法找到顯示此功能實現的示例。
有沒有人可以向我展示此功能的用法,您將擁有一個簡單的自定義選項(可能還有一個標簽和值,每個選項標簽左側還包括一個 SVG 圖形)。
提前謝謝了
對於大多數用例,您可能不需要替換完整的 Option 組件。 如果您希望保持與 Option 相同的整體結構和外觀,但希望顯示多個文本塊、圖像或對每個選項的正文進行一些其他特殊處理,則有一個更簡單的方法道路。
那就是使用formatOptionLabel
渲染道具。
import React from "react";
import ReactDOM from "react-dom";
import Select from "react-select";
const options = [
{ value: "Abe", label: "Abe", customAbbreviation: "A" },
{ value: "John", label: "John", customAbbreviation: "J" },
{ value: "Dustin", label: "Dustin", customAbbreviation: "D" }
];
const formatOptionLabel = ({ value, label, customAbbreviation }) => (
<div style={{ display: "flex" }}>
<div>{label}</div>
<div style={{ marginLeft: "10px", color: "#ccc" }}>
{customAbbreviation}
</div>
</div>
);
const CustomControl = () => (
<Select
defaultValue={options[0]}
formatOptionLabel={formatOptionLabel}
options={options}
/>
);
ReactDOM.render(<CustomControl />, document.getElementById("root"));
https://codesandbox.io/embed/reactselect-formatoptionlabel-bde1q
https://react-select.com/props - 搜索 formatOptionLabel
您可以通過在 components 屬性中包含您的覆蓋來替換任何組件。
<Select components={{Option: MyOption}} />
就像是:
const MyOption = props => {
const { innerProps, innerRef } = props;
return (
<article ref={innerRef} {...innerProps} className="custom-option">
<h4>{props.data.artist}</h4>
<div className="sub">{props.data.title} </div>
</article>
);
};
<Select components={{Option: MyOption}} />
innerRef
和innerProps
屬性非常重要,因為它們繼承了Option 所需的hover 和onClick 之類的東西。 該data
在道具就是你的選擇數據。
通常,您確實想使用formatOptionLabel
道具(沒有額外的組件)。 但如果你不這樣做,你可以通過這種方式覆蓋Option
組件:
import Select, { components } from 'react-select';
const CustomOption = ({ children, ...props }) => {
return (
<components.Option {...props}>
<img src={...} />
{children}
</components.Option>
);
};
function App() {
return (
<Select components={{Option: CustomOption}} ... />
);
}
在這里,我重用了庫存組件( components.Option
)。 這樣我就不需要關心innerRef
什么的了。
如果您想在選擇時設置您的選項的樣式,您可以使用如下自定義選項:
const customOption = (props) => (
{props.isSelected ? (
<img className="custom-option__img" src={IconCheck} alt="" />
) : (
''
)}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.