React 使用扩展运算符向克隆元素添加新道具

React add new props to cloned element with spread operator

我有这样一个容器:

const ReactContainer = ({ children, ...rest }) => React.cloneElement(children, rest);

现在,我想向克隆的元素添加新道具 - countflag

所以我尝试了这个:

const ReactContainer = ({ children, ...rest }) => {
    const count = 0;
    const flag = false;

    return React.cloneElement(children, {count, flag}, rest);
};

但这行不通,我尝试了其他变体。为了简单起见,我如何将这些新道具添加到克隆元素中以保持展开运算符?

请试试这个:

const ReactContainer = ({ children, ...rest }) => {
    const count = 0;
    const flag = false;

    return React.cloneElement(children, {...rest, count, flag});
};

请注意,在上面的示例中,组件函数定义中使用的 ...rest 相当于 rest parameters syntax while in cloneElement it acts as spread syntax