简体   繁体   中英

React Native Arrow Syntax Explanation

I am reviewing some code and was unable to find a breakdown of this arrow function syntax. Could someone help explain what the parameters ({ match, onOpen }: MatchListItemProps) mean?

import React from 'react';
import { ListItem } from 'react-native-elements';
import { StyleSheet } from 'react-native';

type MatchListItemProps = {
  match: User,
  onOpen: Function
};

const styles = StyleSheet.create({});

const TestScreen = ({ match, onOpen }: MatchListItemProps) => {
  const { name, image, message } = match;
  return (....

Could someone help explain what the parameters ({ match, onOpen }: MatchListItemProps) mean?

This code is using typescript and destructuring. Let me get rid of both for a second, then add them back in. Here it is in pure javascript without destructuring:

const TestScreen = (props) => {
  let match = props.match;
  let onOpen = props.onOpen;

Now i'll add back in the typescript. A variable can be followed by a colon and then a type. This information is used to catch type errors at compile time.

const TestScreen = (props: MatchListItemProps) => {
  let match = props.match;
  let onOpen = props.onOpen;

And then adding in the destructuring. This is a shorthand to pluck values off an object and assign them to local variables:

const TestScreen = ({ match, onOpen }: MatchListItemProps) => {

Since the parameter is an object, you can deconstruct it inside the parameter.

For instance, take a look at this code

let person = {
   name: 'Felipe',
   age: '23'
}

You could take the values in this form

let name = person.name
let age = person.age

Or you could use a shortcut with destructuring assignment

let { name, age } = person

Finally, if the variable person inside a parameter, you can deconstruct it inside the very parameter

logPersonNameAndAge = ({ name, age }) => {
   console.log(name)
   console.log(age) 
}

So that you could call it passing the entire object

logPersonNameAndAge(person)

Your code is TypeScript, not just JavaScript. : MatchListItemProps is a type annotation that's used by TypeScript, which is used to catch many common errors at compile time instead of at runtime. ({ match, onOpen }) => { ... is a destructuring, which means the function takes an object, and brings into scope variables called match and onOpen containing whatever was in the object with those names. It's roughly equivalent to obj => { let match = obj.match, onOpen = obj.onOpen; ... obj => { let match = obj.match, onOpen = obj.onOpen; ... . In turn, const TestScreen = obj => { ... is a lambda, which is roughly equivalent to function TestScreen(obj) { ... .

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