最近,我在React Nexus上發表了關於「輔助功能和電視應用程式」的演講。我不斷收到的一個問題是:“作為 ReactJS 開發人員,開始使用 React Native 有多容易?”

簡而言之,對於 ReactJS 開發人員來說,從 React Native 開始會很容易。

在這篇部落格中,我將分享ReactJS的五個概念,ReactJS開發人員可以在React Native中使用。

1. 元件

在 React Native 中,您將像在 ReactJS 中一樣建立元件。概念和最佳實踐保持不變。

在下面的程式碼中,您可以看到React Native元件語法與ReactJS類似

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

const GreetingComponent = () => {
  return (
    <View>
      <Text>Hello, Neha!</Text>
    </View>
  );
};
export default GreetingComponent;

2. props 和 state

在 React Native 中,props 和 state 的工作方式與 ReactJS 中相同。要在元件之間進行通信,您將使用 props。若要更新值,您將使用狀態。

在下面的 React Native 程式碼中,我們使用類似 ReactJS 的 props name

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

const GreetingComponent = ({ name }) => {
  return (
    <View>
      <Text>Hello, {name}!</Text>
    </View>
  );
};
export default GreetingComponent;

3. hooks

就像在 ReactJS 中一樣,您可以使用 React Native 中的所有鉤子,例如 useState()、useMemo()、useEffect() 等。

在下面的 React Native 程式碼中,我們像 ReactJS 一樣使用useState()

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

const GreetingComponent = () => {
  const [name, setName] = useState('John');

  const changeName = () => {
    setName('Jane');
  };

  return (
    <View style={styles.container}>
      <Text>Hello, {name}!</Text>
      <Button title="Change Name" onPress={changeName} />
    </View>
  );
};

export default GreetingComponent;

4. 測試

如果您是 React 測試程式庫的粉絲,好訊息是您可以使用相同的程式庫在 React Native 中進行測試。

import React from 'react';
import { render, fireEvent } from '@testing-library/react-native';
import GreetingComponent from './GreetingComponent';

test('it renders correctly and changes name on button press', () => {
  // Render the component
  const { getByText } = render(<GreetingComponent />);

  // Assert initial state
  expect(getByText('Hello, John!')).toBeTruthy();

  // Find the button and simulate a press
  const button = getByText('Change Name');
  fireEvent.press(button);

  // Assert that the name has changed
  expect(getByText('Hello, Jane!')).toBeTruthy();
});

5.JSX

在 React Native 中,有一些元件可用於在 JSX 中建立視圖。但是,在 ReactJS 中,您可以使用任何有效的 HTML DOM 元素。

在下面的 React Native 程式碼中, ViewText是 React Native 元件。這些元件用於建立應用程式的視圖。

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

const GreetingComponent = () => {
  return (
    <View>
      <Text>Hello, Neha!</Text>
    </View>
  );
};
export default GreetingComponent;

快樂學習!


原文出處:https://dev.to/hellonehha/how-to-start-with-react-native-as-reactjs-developer-2d61


共有 0 則留言