In my articles, I'm going to be using either expo or snack online IDE and android emulator.
在我的文章中,我將使用expo或點心在線IDE和android模擬器。
React Hooks is simply an awesome tool that helps us use states and other react features without writing a class component. That is, it allows you to operate react js states inside function components.
React Hooks只是一個了不起的工具,它可以幫助我們使用狀態和其他react功能而無需編寫類組件。 也就是說,它允許您在功能組件內部操作react js狀態。
The Hook we are using in this tutorial is called the useState Hook?because there is also the effect hook.
我們在本教程中使用的Hook稱為useState Hook,因為也有效果掛鉤。
The useState hook takes an argument which is the initial state of the state you are building.
useState掛鉤接受一個參數,該參數是您正在構建的狀態的初始狀態。
The developers of this say; It returns the current state value and a function that allows you to update it when it is called in an event handler.
開發者這樣說; 它返回當前狀態值和一個函數,該函數允許您在事件處理程序中調用它時對其進行更新。
Here are sample and output.
這是示例和輸出。
Open your App's App.js file and type the following
打開您應用的App.js文件,然后輸入以下內容
import * as React from 'react';
import {useState} from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
export default function App () {
const [Msg,setMsg]= useState('Includehelp');
return (
<View style={styles.container}>
<Text> Hello {Msg} </Text>
<Button
title='click'
onPress={()=>setMsg('my name is Godwill')}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Output
輸出量
From the code above, you can see the format of creating a new react js hook. The hook is immediately before the return statement.
從上面的代碼中,您可以看到創建新的react js鉤子的格式。 掛鉤在return語句之前。
The brackets after the const keyword contain the state called Msg and the setMsg which allows us the reset the Msg state anytime from the code.
const關鍵字后的方括號包含稱為Msg的狀態和setMsg ,這使我們可以隨時從代碼中重置Msg狀態。
Take note of importing useState from 'react' and not react-native.
請注意從“ react”而不是“ react-native”導入useState。
The state is then reset after the button Press which changes the statement in our output.
然后,在按下按鈕后,狀態將被重置,按鈕將更改輸出中的語句。
So that's the format and brief explanation on hooks.
這就是鉤子的格式和簡要說明。
Thanks for coding with me! See you @ the next article. Feel free to drop a comment or question. God Bless You!
感謝您與我編碼! 下次見。 隨意發表評論或問題。 上帝祝福你!
翻譯自: https://www.includehelp.com/react-js/how-to-use-react-js-hooks-in-react-native.aspx