什么是反应方式来做到这一点?

What is a react way to do this?

我有一个非常基本的场景,我有一堆 selectable/clickable 元素并且想要突出显示最后一个 selected/clicked。这是我的 jquerish 版本,我将特定的 css class 添加到所选元素并从其兄弟元素中删除 class 。有没有更好的方法可以用 React 做到这一点?

function Controls(props) {

    const getSiblings = (element) => {
        let siblings = [];
        if (!element.parentNode) {
            return siblings;
        }

        let sibling  = element.parentNode.firstChild;
        while (sibling) {
           if (sibling.nodeType === 1 && sibling !== element) {
               siblings.push(sibling);
           }
           sibling = sibling.nextSibling;
        }
        return siblings;
    };

    const handleClick = (event) => {
        event.target.classList.add("symbol-preview-selected");
        let siblings = getSiblings(event.target);
        siblings.map((e) => {
            e.classList.remove("symbol-preview-selected")
        });
    };

    return(
        <div className="grid-control-container">
            <div className="flex-row-container">
                <span style={{marginRight: "4px"}}>Color:</span>
                <div className="flex-row-container">
                    {[...Array(10).keys()].map((i) => <div className={`symbol-preview symbol-`+i} onClick={handleClick} key={i.toString()}/>)}
                </div>
            </div>
        </div>
    );    
}

改为将点击的元素索引放入状态。

function Controls(props) {
    const [selectedIndex, setSelectedIndex] = useState(-1);
    const makeHandleClick = i => () => {
        setSelectedIndex(i);
    };
    return (
        <div className="grid-control-container">
            <div className="flex-row-container">
                <span style={{ marginRight: "4px" }}>Color:</span>
                <div className="flex-row-container">
                    {[...Array(10).keys()].map((i) => (
                        <div
                            className={'symbol-preview symbol-' + i + (i === selectedIndex ? ' symbol-preview-selected' : '')}
                            onClick={makeHandleClick(i)}
                            key={i}
                        />
                    ))}
                </div>
            </div>
        </div>
    );
}