React 中的这三个点在做什么?

新手上路,请多包涵

... 在这个 React(使用 JSX)代码中做了什么,它叫什么?

<Modal {...this.props} title='Modal heading' animation={false}>

原文由 Thomas Johansen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 921
2 个回答

那是 财产传播符号。它是在 ES2018 中添加的(数组/可迭代的传播更早,ES2015),但它通过编译在 React 项目中得到了很长时间的支持(作为“ JSX 传播属性”,即使你也可以在其他地方做,不仅仅是属性)。

{...this.props} props 中的“自己的”可枚举属性展开为您正在创建的 Modal 元素上的离散属性。例如,如果 this.props 包含 a: 1b: 2 ,那么

<Modal {...this.props} title='Modal heading' animation={false}>

将与

<Modal a={this.props.a} b={this.props.b} title='Modal heading' animation={false}>

但它是动态的,所以任何“自己的”属性都包含在 props 中。

由于 childrenprops 中是“自己的”属性,因此 spread 将包括它。因此,如果它出现的组件有子元素,它们将被传递给 Modal 。将子元素放在开始标签和结束标签之间只是语法糖——很好的一种——用于将 children 属性放在开始标签中。例子:

 class Example extends React.Component {
 render() {
 const { className, children } = this.props;
 return (
 <div className={className}>
 {children}
 </div>
 );
 }
 }
 ReactDOM.render(
 [
 <Example className="first">
 <span>Child in first</span>
 </Example>,
 <Example className="second" children={<span>Child in second</span>} />
 ],
 document.getElementById("root")
 );
 .first {
 color: green;
 }
 .second {
 color: blue;
 }
 <div id="root"></div>

 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

扩展表示法不仅适用于该用例,而且适用于创建具有现有对象的大部分(或全部)属性的新对象 - 当您更新状态时会出现很多情况,因为您无法修改状态直接地:

 this.setState(prevState => {
 return {foo: {...prevState.foo, a: "updated"}};
 });

这将 this.state.foo 替换为一个新对象,该对象具有与 foo 相同的所有属性,除了 a 属性,它变为 "updated"

 const obj = {
 foo: {
 a: 1,
 b: 2,
 c: 3
 }
 };
 console.log("original", obj.foo);
 // Creates a NEW object and assigns it to `obj.foo`
 obj.foo = {...obj.foo, a: "updated"};
 console.log("updated", obj.foo);
 .as-console-wrapper {
 max-height: 100% !important;
 }

原文由 T.J. Crowder 发布,翻译遵循 CC BY-SA 4.0 许可协议

... 称为 扩展属性,顾名思义,它允许扩展表达式。

 var parts = ['two', 'three'];
var numbers = ['one', ...parts, 'four', 'five']; // ["one", "two", "three", "four", "five"]

在这种情况下(我将简化它)。

 // Just assume we have an object like this:
var person= {
    name: 'Alex',
    age: 35
}

这个:

 <Modal {...person} title='Modal heading' animation={false} />

等于

<Modal name={person.name} age={person.age} title='Modal heading' animation={false} />

所以简而言之, 我们可以说 这是一个 巧妙 的捷径。

原文由 Mehdi Raash 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题