Since React Native uses the same API structure as React, it is necessary to understand and learn React, and this section takes you to a quick introduction to React.

import React from 'react';
import {Text} from 'react-native';

const FirstCompose = () => {
  return <Text>Hello</Text>;
};

export default FirstCompose;


This is the simplest code for a React component, the first step involves importing the components or libraries you need via import , here React and Text are imported, and a component can be declared via a function whose return value can be rendered. The final step is to just export your component via export .


The focus function returns <Text>Hello</Text> : this is the syntax used by React to describe UI elements (JSX) and is part of the JavaScript syntax

JSX


Note that the JSX syntax is included in the React library, so you need to import it at the beginning of the file import React from 'react' . Since JSX is part of JavaScript, you can still use the rest of the JavaScript syntax, just wrap it in {}.

import React from 'react';
import {Text} from 'react-native';

const getFullName = (
  firstName: string,
  secondName: string,
  thirdName: string,
) => {
  return firstName + ' ' + secondName + ' ' + thirdName;
};

const Cat = () => {
  return <Text>Hello, I am {getFullName('Rum', 'Tum', 'Tugger')}!</Text>;
};

export default Cat;

 Customizing Complex Components


We can also combine multiple components together to export, in Android development, we put the View into parent layouts such as LinearLayout , FrameLayout , RelativeLayout and arrange and combine them, in React we just need to use <View> to combine multiple components. <View></View> It can also be abbreviated as <></>

import React from 'react';
import {Text, View} from 'react-native';

const Cat = () => {
  return (
    <View>
      <Text>I am also a cat!</Text>
    </View>
  );
};

const Cafe = () => {
  return (
    <View>
      <Text>Welcome!</Text>
      <Cat />
      <Cat />
      <Cat />
    </View>
  );
};

export default Cafe;


In this example, the other files simply use <Cafe> to render all the components at once. One of the components contains another component called the parent component

Prop


The previous section only covered how to define a complex component, but didn’t provide user-selectable parameters. Adding parameters to a custom component is as simple as adding parameters to the function you declare:.

import React from 'react';
import {Text, View} from 'react-native';

type CatProps = {
  name: string;
};

const Cat = (props: CatProps) => {
  return (
    <View>
      <Text>Hello, I am {props.name}!</Text>
    </View>
  );
};

const Cafe = () => {
  return (
    <View>
      <Cat name="Maru" />
      <Cat name="Jellylorum" />
      <Cat name="Spot" />
    </View>
  );
};

export default Cafe;


The TypeScript syntax is used to specify the parameter types, and the parameters are used in the same way as in a normal class call, with the main focus being on the passing of the parameter <Cat name="Maru" /> when the function is called. This is one way of passing a parameter, there is another case, you may be curious, for example: <Text>Hello</Text> In this case the Hello here after passing belongs to that parameter?


The answer is: Hello is the value passed to the children property. children The attribute is a special property that allows you to nest other components or text within a component. Let’s check the source code in passing to see if this is the case.

export interface TextProps extends TextPropsIOS, TextPropsAndroid, AccessibilityProps {
    /**
     * Specifies whether fonts should scale to respect Text Size accessibility settings.
     * The default is `true`.
     */
    allowFontScaling?: boolean | undefined;

    children?: React.ReactNode;
    
    
    //...    
}


Indeed the children attribute can be found and he is of type React.ReactNode . So let’s infer if the

<Text><Text>...</Text></Text>

 Would this also display properly, or even do more customization?

State


So far, our pages have been static. We can use useState to define a modifiable variable that will trigger a re-render when it changes

import React, {useState} from 'react';
import {Button, Text, View} from 'react-native';

type CatProps = {
  name: string;
};

const Cat = (props: CatProps) => {
  const [isHungry, setIsHungry] = useState(true);

  return (
    <View>
      <Text>
        I am {props.name}, and I am {isHungry ? 'hungry' : 'full'}!
      </Text>
      <Button
        onPress={() => {
          setIsHungry(false);
        }}
        disabled={!isHungry}
        title={isHungry ? 'Pour me some milk, please!' : 'Thank you!'}
      />
    </View>
  );
};

export default Cat;


In this example, the variable isHungry is declared and setIsHungry is used to change its value when the button is clicked. Trigger a re-rendering to display the new text

useState

const [state, setState] = useState(initialState);


useState accepts an initial value, returns the corresponding variable and the method to modify it, and assigns it in turn to const [state, setState] , a syntax called: deconstructed assignment. When setState is called to modify the value, it triggers the component to re-render with the new value.


  • initialState : Not only can you pass fixed values, but you can also pass a function, which can’t have an input and must have an output. If you pass just the name of the function then the function will only be called the first time it is initialized, if you are passing a function call then it will be called every time it is rendered
function createInitialTodos() {
    return ...
}

function TodoList() {
    const [todos, setTodos] = useState(createInitialTodos());
  
    const [todos, setTodos] = useState(createInitialTodos);

}

  • setState : The function prototypes are: setState(S) or setState((prevState: S) => S) This indicates that the setState call can also pass a function, which has the last value as its input and needs to return the changed value. For objects, the comparison is done via Object.is
//1. 
setState(false)

//2. 
setState((pre) => {
    //do something
    let ret = !pre
    return ret
})

  • state : represents the current value, the initial value is based on the initialState you passed in.

  1. React will wait for all the States to finish rendering before batching, if you want to render immediately you can use flushSync

  2. When you call the set method, you don’t change the value of the state immediately, you wait for it to be rendered.
const [name, setName] = useState('Taylor');

function handleClick() {
  setName('Robin');
  console.log(name); // Still "Taylor"!
}

  1. If the parameter you pass to set is a function, the function will be added to the queue and executed in turn on the next rendering
import { useState } from 'react';

export default function Counter() {
  const [age, setAge] = useState(42);

  function increment() {
    setAge(a => a + 1);
  }

  return (
    <>
      <h1>Your age: {age}</h1>
      <button onClick={() => {
        increment();
        increment();
        increment();
      }}>+3</button>
    </>
  );
}

function increment() {
    setAge(a + 1);
    setAge(a + 1);
    setAge(a + 1);
}


  1. In the case where the state is an object or an array, since the state is a read-only property, you should replace it instead of modifying the internal value.
const [from, setFrom] = useState({firstName:"AAA"})

setForm({
  ...form,
  firstName: 'Taylor'
});

useEffect

useEffect(setup, dependencies?)

  • dependencies : is an array containing the values that useEffect listens for, and when these values change, the setup function is called


    • If there are values in the passed array: then the setup function is called when it is first rendered and after the values in the array have changed.

    • If the passed array is an empty array: the setup function will only be called when the first rendering occurs

    • If this parameter is not passed at all: then every time it is rendered, the setup function is called

  • setup The function can then return a “cleanup function”, which will call the setup function the first time it is rendered, and then if you provide a cleanup function, it will use the old dependencies to execute the cleanup function first, and then use the new value to execute the setup function. When the component is removed, the cleanup function is called one last time.
import { useEffect } from 'react';
import { createConnection } from './chat.js';

function ChatRoom({ roomId }) {
  const [serverUrl, setServerUrl] = useState('https://localhost:1234');

  useEffect(() => {
    const connection = createConnection(serverUrl, roomId);
    connection.connect();
    return () => {
      connection.disconnect();
    };
  }, [serverUrl, roomId]);
}

useRef

useRef(initialValue) 


Returns an object containing only the current property, which you set to the initial value of initialValue . The useRef returns the same object when it is next rendered, and you can change the value of current to record some information. It differs from useState in that the rendering is not triggered when you modify current .

 Another use of ref is to control the DOM, as in the following example

import { useRef } from 'react';

export default function Form() {
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={handleClick}>
        Focus the input
      </button>
    </>
  );
}


A ref is first declared using null and then assigned to the DOM’s ref property. When React creates this DOM and renders it to the screen, React sets the current of the ref to this DOM. you can then manipulate it via current. When the DOM disappears from the screen, React sets current to null.

memo

const MemoizedComponent = memo(SomeComponent, arePropsEqual?)

 memo allows a component to skip rendering when a property is unchanged


  • SomeComponent : a component you need to work with, the memo will return a new one exactly like it

  • arePropsEqual : A function for the user to determine if an attribute has changed, with the function prototype: (preProp, newProp)=> bool If this parameter is not specified, then it will use the object.is

By hbb

Leave a Reply

Your email address will not be published. Required fields are marked *