简体   繁体   中英

Reactjs Trying to make dropdown, how to not show the selected list on the lists?

I'm trying to customizing this dropdown component. https://codesandbox.io/s

state = {
    activeOptionIndex: -1,
    isOpen: false,
};

getAdditionalProps = (index, props) => ({
    onSelect: this.onSelect,
    index,
    selected: index === this.state.activeOptionIndex,
    ...props,
});

getChildrenOptionssWithProps = () => {
    return Children.map(this.props.children, (child, index) =>
        cloneElement(child, this.getAdditionalProps(index, child.props)),
    );
};

getActiveOptionLabel = () => {
    const { children } = this.props;
    const { activeOptionIndex } = this.state;
    const currentChildren = children[activeOptionIndex];

    if (currentChildren) {
        return currentChildren.props.children;
    }

    return false;
};

toggleList = () => {
    this.setState({ isOpen: !this.state.isOpen });
};

onSelect = (optionIndex, value) => {
    const { onSelect } = this.props;

    this.setState({
        activeOptionIndex: optionIndex,
        isOpen: false,
    });

    if (onSelect !== 'undefined') onSelect(value);
};

render() {
    const childrenOptionssWithProps = this.getChildrenOptionssWithProps();
    const label = this.getActiveOptionLabel();

    return (
        <div className="Dropdown">
            <Button onClick={this.toggleList} text={label || 'Выберите...'} />
            {this.state.isOpen && (
                <div className="Dropdown__list">{childrenOptionssWithProps}</div>
            )}
        </div>
    );
}

}

I don't wanna show the selected list on all the lists. Let's say there are list A, list B, list C. and when list B is selected, I dont want this list B to be shown on all the lists. so only list A and list B will be showing on the lists.

getAdditionalProps()

getChildrenOptionssWithProps()

I think these two functions are the points to solve this problem but have no idea how to manage it... Before the mapping from getChildrenOptionssWithProps(), I can add filter function i guess?

Can anyone please help me??

I modified your getChildrenOptionssWithProps function as follows and it seems to be doing what you are looking for.

getChildrenOptionssWithProps = () => {
    return Children.map(this.props.children, (child, index) => {
        if (index !== this.state.activeOptionIndex){
            return cloneElement(child, this.getAdditionalProps(index, child.props));
        }
        return;
    }
    );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM