import React, { Component } from "react";
class Learning extends Component {fName = React.createRef();onForm = e => {
e.preventDefault();console.log(this.fName.value.value);};render() {return (<div><form onSubmit={this.onForm}><inputtype="text" placeholder="Enter Your First Name" ref={this.fName} /><button type="submit" style={BtnStyle}>Submit</button></form></div>);}}export default Learning;
答案 0 :(得分:1)
您必须在ref上使用current
属性:
console.log(this.fName.current.value);
https://reactjs.org/docs/refs-and-the-dom.html#accessing-refs
但是请考虑使用更改事件和状态
class Learning extends Component {
constructor() {
this.state = {
fName: ''
}
}
updateName = (e) => {
this.setState({fName: e.target.value});
}
onForm = (e) => {
e.preventDefault();
console.log(this.state.fName):
}
render() {
return (
<form onSubmit={this.onForm}>
<input onChange={this.updateName} />
</form>
):
}
}
答案 1 :(得分:0)
再次检查react docs,使用React.createRef()
来访问使用this.fName.current.XXX
创建的引用。