使用React的事件处理程序来阻止表单默认行为
在React中,表单提交会默认刷新整个页面。要避免这种情况,可以将事件处理程序传递给表单,并使用preventDefault方法来阻止默认行为。
示例代码:
class Form extends React.Component { constructor(props) { super(props); this.state = {inputValue:''}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); }
handleChange(event) { this.setState({inputValue: event.target.value}); }
handleSubmit(event) { event.preventDefault(); // submit logic here }
render() { return (
); } }在上面的代码中,handleSubmit方法使用event.preventDefault()来阻止表单刷新页面。这样,在表单提交时,只会运行handleSubmit方法,而不会刷新整个页面。
上一篇:表单提交后,值未保存。