使用状态来反应功能组件 [英] React functional component using state

查看:68
本文介绍了使用状态来反应功能组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用如下所示的函数来实现React智能组件 https://hackernoon.com/react无状态功能组件有九个优势可能会让您忽略了997b0d933dbc

I'm trying to implement a React smart component using functions as shown here https://hackernoon.com/react-stateless-functional-components-nine-wins-you-might-have-overlooked-997b0d933dbc

但是,我的问题是我需要维护状态,在这种情况下该如何做,例如,我需要访问并设置

My problem is however that I need to maintain state, and how do I do it in this scenario, for example I need to access and set

this.state = {Title: 'Login'};

推荐答案

从React 16.8.0开始,您可以使用useState的Hook实例化功能组件中的State自定义.像这样...

From React 16.8.0 You can use Hooks using useState to instantiate a State custom in your Functional Component. Like This...

import React, {useState} from 'react';

const AddButon = ({handleAddValue}) => {
  return <button onClick={handleAddValue}>Add</button>
}

const App = (props) =>{

  const [value, setValue] = useState(0);

  const handleAddValue = () => {
    const newValue = value+1;
    setValue(newValue);
  }

  return (
    <div>
      <div>The Value is: {value}</div>
      <AddButon handleAddValue={handleAddValue} />
    </div>);
}

如果您想了解有关此新功能的更多信息,请访问以下链接.

If you want to read more about this new functionality, follow the following link.

https://reactjs.org/docs/hooks-intro.html

这篇关于使用状态来反应功能组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆