简体   繁体   中英

Rewrite react functional component in vanilla javascript

I'm having a hard time understanding how the functional component in React through es6 gets the props as an argument by placing it in an object. Is this part of es6's feature? Or is it part of React to magically pull the props through as an argument without having to refer to this.props... ? If someone can rewrite the below component in vanilla js for me with a function (not React.createElement as Babel repl does), that would be very helpful.

const Repos = ({repos}) => {
  return (
    <div>
      <h3> User Repos </h3>
      <ul className="list-group">
        {repos.map((repo, index) => {
          return (
            <li className="list-group-item" key={repo.name}>
              <h4><a href={repo.html_url}>{repo.name}</a></h4>
              <p>{repo.description}</p>
            </li>
          )
        })}
      </ul>
    </div>
  )
}

It's using destructuring and yes it's part of the standard.

What it is basically doing is the equivalent of saying

const repos = props.repos;

Which you would do if you had props as a parameter

const Repos = (props) => {
  const repos = props.repos;
  return (
    <div>
      (...)
    </div>
  )
}

In ES3 you would also have to spell out the function keyword and use var instead of const .

var Repos = function(props) {
  var repos = props.repos;
  return (
    <div>
      (...)
    </div>
  )
}

So the only React-magic going on is the use of JSX to inline markup within the code.

This is a destructuring assignment and part of the ES2015 spec. Repos is a function that expects an Object . When Repos is called it evaluates the destructuring pattern and assigns the result to its single argument:

 const Repos = ({repos}) => { return repos; } const props = {repos: [1,2,3]}; const foo = {bar: "baz"}; console.log(Repos(props)); console.log(Repos(foo)); 

The name of the property ( repos ) and the name of the argument that is actually passed to Repos are the same, because the given destructuring pattern doesn't define a different one (in fact ({repos}) is shorthand for ({repos:repos}) ). However, a different name makes it clearer what is happening under the hood:

 const Repos = ({repos:arg}) => { return arg; } const props = {repos: [1,2,3]}; console.log(Repos(props)); 

Please note that this has nothing to do with default parameters.

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