简体   繁体   中英

Spread or Rest operator clarification ES6

I'm following a react tutorial and I need a little clarification. In the render function of the App.js component, the spread operator is used on the contest object exposed by mapping over the contests array. How is the ContestPreview.js Component able to use it as props without the property being named and why is the spread operator being used in this instance?

Thanks.

App.js

import React from 'react';
import Header from './Header';
import ContestPreview from './ContestPreview';
import data from '../testData';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      pageHeader: 'Naming Contests',
      contests: []
    };
  }

  componentDidMount() {
    this.setState({
      contests: data.contests
    });
  }

  render() {
    return (
      <div className='App'>
        <Header message={this.state.pageHeader} />
        <div>
          {this.state.contests.map(contest =>
            <ContestPreview key={contest.id} {...contest}
             />
          )};
        </div>
      </div>
    );
  }
}

export default App;

ContestPreview.js

import React from 'react';

const ContestPreview = (contest) => (
  <div className='ContestPreview'>
    <div className='category-name'>
      {contest.categoryName}
    </div>
    <div className='contest-name'>
      {contest.contestName}
    </div>
  </div>
);

export default ContestPreview;

In the context of

<div {...props} />

the spread syntax ( ... ) here is specifically JSX, it has its own JSX-defined behavior because it is not a normal ES6 spread, nor is it the proposed object spread.

The JSX spread syntax will take all of the properties of the given object, and pass them as part of props to the child component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM