event.preventDefault( ) 在 React 中不起作用
event.preventDefault( ) is NOT working in React
无法在控制台中获取值!
我做错了什么?
下面附上React的功能组件
处理函数
import React, { useState, useRef } from 'react';
const SimpleInput = (props) => {
const nameInputRef = useRef();
const [enteredName, setEnteredName] = useState('');
const nameInputChangeHandler = (event) => {
setEnteredName(event.target.value);
};
const formSubmissionHandler = (event) => {
event.preventDefault();
console.log(enteredName);
const enteredName = nameInputRef.current.value;
console.log(enteredName);
};
JSX 代码
return (
<form>
<div className="form-control" onSubmit={formSubmissionHandler}>
<label htmlFor="name">Your Name</label>
<input
ref={nameInputRef}
type="text"
id="name"
onChange={nameInputChangeHandler}
/>
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);
};
export default SimpleInput;
formSubmissionHandler
应该在 form
元素而不是 div
元素上。
return (
<form onSubmit={formSubmissionHandler}>
<div className="form-control">
<label htmlFor="name">Your Name</label>
<input
ref={nameInputRef}
type="text"
id="name"
onChange={nameInputChangeHandler}
/>
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);
无法在控制台中获取值! 我做错了什么?
下面附上React的功能组件
处理函数
import React, { useState, useRef } from 'react';
const SimpleInput = (props) => {
const nameInputRef = useRef();
const [enteredName, setEnteredName] = useState('');
const nameInputChangeHandler = (event) => {
setEnteredName(event.target.value);
};
const formSubmissionHandler = (event) => {
event.preventDefault();
console.log(enteredName);
const enteredName = nameInputRef.current.value;
console.log(enteredName);
};
JSX 代码
return (
<form>
<div className="form-control" onSubmit={formSubmissionHandler}>
<label htmlFor="name">Your Name</label>
<input
ref={nameInputRef}
type="text"
id="name"
onChange={nameInputChangeHandler}
/>
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);
};
export default SimpleInput;
formSubmissionHandler
应该在 form
元素而不是 div
元素上。
return (
<form onSubmit={formSubmissionHandler}>
<div className="form-control">
<label htmlFor="name">Your Name</label>
<input
ref={nameInputRef}
type="text"
id="name"
onChange={nameInputChangeHandler}
/>
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);