reactjs - 如何将我的代码 ( this.state ) 转换为 useState()?
问题描述
我需要将以下代码转换为无状态功能组件,而不使用类。不幸的是,我不太擅长将基于类的组件解释为功能组件,所以我不确定语法到底是什么。
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
isOpen: true,
};
}
render() {
return (
<IconSettings iconPath="/assets/icons">
{this.state.isOpen ? (
<AlertContainer>
<Alert
dismissible
icon={<Icon category="utility" name="user" />}
labels={{
heading: 'Logged in as John Smith (johnsmith@acme.com).',
headingLink: 'Log out',
}}
onClickHeadingLink={() => {
console.log('Link clicked.');
}}
onRequestClose={() => {
this.setState({ isOpen: false });
}}
/>
</AlertContainer>
) : null}
</IconSettings>
);
}
}
解决方案
这是正确的使用方法useState
,如果您使用,redux
您可以将其集成useSelector
以获得初始状态。
这里的例子:
import React, { useState } from 'react'
function Example() { // or function Example(props) { , if you need to pass props to the component
const [isOpen, setOpen] = useState(true) // <-- initial state for "isOpen"
const onRequestClose = () => {
setOpen(false)
}
return (
<>
// ... code
<SomeComponent
onRequestClose={onRequestClose}
// ... rest of code
/>
// ... more code
</>
)
}
推荐阅读
- javascript - javascript数组 - 如何过滤一个嵌套级别并仅获取该值
- google-analytics - 如何跟踪 next.js 项目中的初始页面浏览量?
- header - 是否有我们可以添加到 gempages (shopify) 以创建标题而不必处理 shopify 的应用程序?
- wordpress - 如何显示内联 form_fields 的复选框 - Wordpress 设置 API 开发
- javascript - 我的视频模式在加载页面上显示为空白,我该如何纠正?
- html - 为什么 ASP.NET Core MinLength 属性没有添加 HTML minlength 属性,而 MaxLength 有?
- c - m68k-elf 目标是否支持 GCC 内联 asm goto?
- protractor - 量角器中的 ARROW_DOWN
- eslint - 如何禁止 Prettier 修改标签
- asp.net-core - HttpGet 请求字符串参数被初始化为 null