【发布时间】:2021-04-16 11:20:29
【问题描述】:
编辑:事件根本不起作用,没有调用 onSubmit 和 onChange 函数。我有另一个具有类似形式的 reactapp,并且 onChange 和 onSubmit 在那里工作正常。
我有一个表单,我不想在单击提交时刷新页面。我尝试使用preventDefault(),但我没有工作。甚至 onChange 也在控制台上打印任何内容。此表单不在页面上,我正在使用 React Router 指向 to='/new' 和 component={NewPost}(NewPost 在 ./components/posts/form)
./components/posts/form.js:
import React, { Component } from "react";
import { connect } from "react-redux";
class NewPost extends Component {
state = {
title: "",
body: "",
status: 0,
};
onSubmit = (e) => {
e.preventDefault();
const post = e;
console.log(post);
};
onChange = (e) => {
console.log(e.target.value);
this.setState({
[e.target.name]: e.target.value,
});
};
render() {
const { title, body, status } = this.state;
return (
<div className="card card-body mt-4 mb-4">
<h2>New Post</h2>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Title</label>
<input
type="text"
name="title"
value={title}
onChange={this.onChange}
className="form-control"
/>
</div>
<div className="form-group">
<label>Content</label>
<textarea
type="text"
name="body"
rows="15"
value={body}
onChange={this.onChange}
className="form-control"
/>
</div>
<div className="form-group">
<button className="btn btn-primary" type="submit">
Submit
</button>
</div>
</form>
</div>
);
}
}
export default NewPost;
App.js:
import React from "react";
import NavBar from "./components/layout/navbar";
import store from "./store";
import { Provider } from "react-redux";
import Dashboard from "./components/posts/dashboard";
import NewPost from "./components/posts/form";
import {
HashRouter as Router,
Route,
Switch,
Redirect,
} from "react-router-dom";
class App extends React.Component {
render() {
return (
<Provider store={store}>
<Router>
<React.Fragment>
<div className="container">
<NavBar />
<Switch>
<Route exact path="/" component={Dashboard}></Route>
<Route exact path="/new" component={NewPost}></Route>
</Switch>
</div>
</React.Fragment>
</Router>
</Provider>
);
}
}
export default App;
【问题讨论】:
-
提供你所有的代码,就像你是路由器和相关组件一样
-
@SomeoneSpecial 事件已断开连接/无法在我的应用程序上运行。我什至没有得到 console.log(e.target.value); 的输出。在我这边。
-
他已经为您制作了一个没有问题的代码框,如果您无法重现问题意味着您在其他地方遇到了与问题无关的问题
-
你试过e.stopPropagation()吗?
标签: javascript reactjs react-router-dom