首页 > 解决方案 > 为什么在传递道具时需要使用扩展运算符

问题描述

下面是代码:

const Info = (props) => (
    <div>
        <h1>Info</h1>
        <p>The info is: {props.info}</p>
    </div>
);

const withAdminWarning = (WrappedComponent) => {
    return (props) => (
        <div>
           <p>This is private info. Please don't share!</p>
           <WrappedComponent {...props}/>   // why need to use spread operator?
        </div>
    );
};

const AdminInfo = withAdminWarning(Info);

ReactDOM.render(<AdminInfo info="There are the details" />, document.getElementById('app'));

我不明白的是,为什么必须这样:

 <WrappedComponent {...props}/>  

而且我不能将对象传递为:

const temp = {info: "There are the details"}
<WrappedComponent temp/>  

那 {...props} 不也是一个对象吗?

标签: javascriptreactjs

解决方案


您不需要使用扩展运算符,您也可以执行类似的操作

const temp = { info: "There are the details }
<WrappedElement temp={temp} />

您可以稍后访问它props.temp.info


推荐阅读