[英]How do I convert my class and render() to a functional component using react hooks?
I'm trying to convert my class to a functional component but I'm having trouble with the isInputActive
.我正在尝试将我的 class 转换为功能组件,但我遇到了isInputActive
。 This is what the class looks like:这就是 class 的样子:
BEFORE前
class HelloWorld extends React.Component {
constructor(props) {
super(props);
this.state = {
isInputActive: false,
};
}
render() {
const focusHandler = () => {
onChange('');
this.setState({
isInputActive: true,
});
};
And in my return()
, I've got this:在我的return()
中,我得到了这个:
<input
onBlur={() => {
this.setState({ isInputActive: false });
}}
/>
So, I tried converting it as seen below:因此,我尝试将其转换为如下所示:
I converted the class to a const:我将 class 转换为 const:
AFTER后
const HelloWorld = ({ isInputActive }) => {
const [isInputActive, setIsInputActive] = useState(false);
Then my render()
was converted as seen here:然后我的render()
被转换为如下所示:
const focusHandler = () => {
onChange('');
setIsInputActive(true);
};
And finally, I assumed that my <input>
in the return()
would look like this (the setState
became useState
which I'm not sure if it's correct either):最后,我假设return()
中的<input>
看起来像这样( setState
变成useState
,我也不确定它是否正确):
onBlur={() => {
useState({ isInputActive: false });
}}
Does anyone know what it should look like?有谁知道它应该是什么样子? to make it work without erroring?让它工作而不会出错? Where I've done const PinInput = ({ isInputActive }) => {
I get an error: Parsing error: Identifier 'isInputActive' has already been declared
我已经完成const PinInput = ({ isInputActive }) => {
我得到一个错误: Parsing error: Identifier 'isInputActive' has already been declared
My code might be wrong so you can ignore the AFTER if you want.我的代码可能是错误的,因此您可以根据需要忽略AFTER 。 I'm just trying to make sure I get rid of the render().我只是想确保我摆脱了渲染()。
Change,改变,
onBlur={() => {
useState({ isInputActive: false });
}}
To,至,
onBlur={() => {
setIsInputActive(false);
}}
Reason you are getting this error, Parsing error: Identifier 'isInputActive' has already been declared
is because, You are already declaring the variable isInputActive
here,您收到此错误的原因, Parsing error: Identifier 'isInputActive' has already been declared
是因为,您已经在此处声明了变量isInputActive
,
const [isInputActive, setIsInputActive] = useState(true);
And it already hold the value of true
.它已经拥有true
的值。
To make it false just do setIsInputActive(false)
..要使其为假,只需执行setIsInputActive(false)
..
You can try replacing your code like this:
import React from "react";
function HelloWorld() {
const [isInputActive, setIsInputActive] = React.useState(true);
return (
<>
<input
onBlur={() => {
setIsInputActive(false);
}}
/>
</>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.