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

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

问题描述

我正在尝试使用此处显示的函数来实现 React 智能组件https://hackernoon.com/react-stateless-functional-components-nine-wins-you-might-have-overlooked-997b0d933dbc

然而,我的问题是我需要维护状态,在这种情况下我该怎么做,例如我需要访问和设置

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

解决方案

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

import React, {useState} from 'react';const AddButon = ({handleAddValue}) =>{return }const App =(道具)=>{const [value, setValue] = useState(0);const handleAddValue = () =>{const newValue = 值+1;设置值(新值);}返回 (<div><div>值是:{value}</div><AddButton handleAddValue={handleAddValue}/>

);}

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

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

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'};

解决方案

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天全站免登陆