简体   繁体   中英

React-native question about app.js main class/function

I'm a beginner in RN and I have only basic JS knowledge, but I need to make a small project in React Native. I've bought a tutorial but I have problem on start.

On the RN wiki, hello world is written like that:

export default class HelloWorldApp extends Component {
      render() {
        return (
          <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
            <Text>Hello, world!</Text>
          </View>
        );
      }
    }

but instructor in my tutorial does like this:

  export default function App() {
   return (
          <Text>Hello, world!</Text>
       );
      }
    }

The result is similar. I understand render() is inner class function and works like default function. Is that correct understanding? If it is, why some people use that and other doesn't. What is difference between these solutions? Does it unlock some options which I don't understand yet?

This is a difference between class (1st option) and functional components (2nd in your example). This is basically up to a programmer to choose the style he likes mosts, with both having benefits and downsides.

If you're new to React, I'd suggest just using any one style that's easier for you to understand.

If you want to know the difference in more details, here's a good article about it .

JavaScript is a great language that has taken the object oriented programming concept of 'Abstraction' to the next level.

In Javascript, everything is an object!

Even a function can be abstracted into an object.

The statement 'export default function App()' will export the function named App as an object named 'App'.

This will make it possible to use the App function the same way like a regular object of class (HelloWorldApp)!

Abstracting a function like an object is a very useful feature. It only takes the new learners a little bit of getting used to the idea!

with classes (your fist exmp.) you can often find approaches from tutorials you find around internet. Goodness for the beginners are lifecycles used in class. In the other hand is luck the functionality as typical function (read lines and functional re-render) therefore your code will be soon confusing. Again in functions (your second exmp.) you will have to use hooks let say useState , setState etc.

If I can suggest to you, continue with your tutorial and learn function scripting, is more valuable and will lead you to learn redux as well (may be) :).

Happy codding

In first class you can add no. of components,but in second class you have to add an outer view to add more components.

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