React中传递props为何必须使用扩展运算符(spread operator)?
{...props}传递组件props,而不能直接用<WrappedComponent temp/>? 先看你的示例代码:
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}/>的方式传递props,而不能直接定义对象const temp = {info: "There are the details"}后以<WrappedComponent temp/>的形式传递?毕竟{...props}本质也是一个对象。
好问题!这其实是JSX语法规则和组件props传递逻辑的核心问题,咱们拆开来解释:
1. <WrappedComponent temp/>的实际含义
在JSX语法里,如果你只写属性名不赋值(比如temp),这是布尔属性的简写方式,它等价于<WrappedComponent temp={true}/>。也就是说,你传递给WrappedComponent的不是temp这个对象本身,而是一个名为temp、值为true的布尔型props。
放到你的例子里,如果你这么写:
const temp = {info: "There are the details"}; <WrappedComponent temp/>
那么Info组件拿到的props会是{temp: true},而不是你期望的{info: "There are the details"}——这就导致props.info是undefined,渲染出来的内容会是The info is: undefined,完全不符合预期。
2. {...props}的作用是什么?
{...props}是ES6扩展运算符在JSX中的应用,它的作用是把props对象中的所有键值对拆解成独立的props传递给组件。
比如你的例子里,props是{info: "There are the details"},使用{...props}就等价于直接写:
<WrappedComponent info={props.info}/>
这种写法的优势在于灵活性:不管props里有多少个属性(比如后续新增id、name等),都能一次性传递给组件,不需要逐个手动写属性名。
3. 如果想用自定义对象传递,正确的写法是什么?
如果你非要用temp这个对象传递props,正确的写法是用扩展运算符拆解它:
const temp = {info: "There are the details"}; <WrappedComponent {...temp}/>
这样就和{...props}的效果完全一致,Info组件能正确拿到info这个props。
或者你也可以手动指定属性:
<WrappedComponent info={temp.info}/>
但这种写法在属性多的时候会很繁琐,不如扩展运算符简洁。
总结一下:JSX里的属性简写是布尔值,不是对象传递;扩展运算符才是把对象的键值对转化为组件props的正确方式。
内容的提问来源于stack exchange,提问作者user11224591

