如何在React Native中使用React JS Hooks?

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

输出量

How to use React JS Hooks in React Native?

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值