首页 > 解决方案 > 在 React 中自定义选择菜单

问题描述

更新!

我正在为下拉菜单创建一个包装器并在几个组件中使用它,所以我需要使这样的菜单通用。问题是我不明白如何将外部变量传递给这样的组件。

我的组件:

const SelectOptionsPaginated = ({
                                    alignment, minWidth, width,
                                    rowData,
                                    column
                                }) => {
..........

const Menu = (props) => {

        const {options} = props;
        const dropdownContainer = useRef(null);
        const [maxMenuHeight, setMaxMenuHeight] = useState(300)
        const [dropDownStyle, setDropDownStyle] = useState({
            position: "absolute",
            minWidth: `${minWidth ? minWidth + "px" : "100%"}`,
            maxWidth: `${width}px`,
            maxHeight: `${maxMenuHeight}px`,
            top: `32px`
        })

        const getDropdownPosition = (elem) => {
            setDropDownStyle({
                ...dropDownStyle,
                ...getDropdownAlignment(elem, setMaxMenuHeight, gridId, options, true)
            })
        };

        useEffect(() => {
            const optionsList = dropdownContainer.current
            if (!optionsList) return
            getDropdownPosition(optionsList)
        }, [options])

        return (
            <div
                className="dropdown-container"
                ref={dropdownContainer}
                style={dropDownStyle}
            >
                <components.Menu {...props} >
                    {props.children}
                </components.Menu>
            </div>
        )
    }

............

    return <AsyncPaginate
        additional={defaultAdditional}
        isMulti={isMulti}
        value={value}
        loadOptions={loadOptions}
        onChange={handleChange}
        escapeClearsValue
        isClearable
        styles={getStylesForSelectorEditor(width, minWidth, newAlignment)}
        components={{Menu}}
    />

诸如minWidth,之类的变量width应该从外部传递给Menu.

我试过类似的东西:

...............
    return <AsyncPaginate
        additional={defaultAdditional}
        isMulti={isMulti}
        value={value}
        loadOptions={loadOptions}
        onChange={handleChange}
        escapeClearsValue
        isClearable
        styles={getStylesForSelectorEditor(width, minWidth, newAlignment)}
        // pseudocode
        components={{<Menu width={100}/>}} or
        components={{Menu(100)}} 

    />

但它不起作用。

我试图谷歌但没有找到明确的信息。我是新来的反应,所以会很感激任何帮助。

标签: reactjs

解决方案


你的意思是这样的吗?

const AsyncPaginate= (props) => {
    const {components} = props;
        return (
            <>
                {components}
            </>
    )
}
    
const Menu = () => { 
    return (
        <>
            something...
            </>
        )
}
    
const App = () => {
    return (
            <>
                <AsyncPaginate components={<Menu />}></AsyncPaginate>
            </>
    )
}

推荐阅读