[英]Convert Uncontrolled Components from : Class extends to Functional Components?
I'm getting trouble in converting the Uncontrolled Components
from class Components into Functional Componnents...我在将Uncontrolled Components
从类组件转换为功能Uncontrolled Components
遇到了麻烦...
Class Components:类组件:
import React from 'react';
class NameForm extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.input = React.createRef();
}
handleSubmit(event) {
console.log('A name was submitted: ' + this.input.current.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default NameForm;
I want to convert into functional component.我想转换成功能组件。 SOmething like this:像这样的东西:
import React,{useState,useEffect} from 'react';
function App() {
const[inputText,setinputText] = useState();
//Rest of codes here::
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
export default App;
I really don't know about converting the constructor.. Any one please help me on this.我真的不知道转换构造函数..任何人请帮助我。
Can be done like this:可以这样做:
import React from "react";
const NameForm = () => {
const inputRef = React.useRef();
const handleSubmit = (event) => {
event.preventDefault();
console.log("A name was submitted: " + inputRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" ref={inputRef} />
</label>
<input type="submit" value="Submit" />
</form>
);
};
export default NameForm;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.