【发布时间】:2019-11-24 10:43:19
【问题描述】:
我正在尝试使用 express-react-views 和 react-bootstrap 编写一个快速应用程序。
我没有采用创建 React 应用程序的常规方式(运行 npx create-react-app my-app),而是设置一个快速应用程序并通过它运行路由。这一切似乎都有效,但现在我正在尝试使用 onSubmit 处理程序创建一个引导表单。
我查看了 react 网站上的代码示例以获取表单:https://reactjs.org/docs/forms.html,但使用下面的代码,我的 handleSubmit 永远不会被调用。如果我将onSubmit 中的代码替换为console.log(‘hello’) 之类的代码,那么当我加载页面时,我会在控制台中看到'hello'。
const React = require('react');
const Jumbotron = require('react-bootstrap').Jumbotron;
const Container = require('react-bootstrap').Container;
const Form = require('react-bootstrap').Form;
const FormGroup = require('react-bootstrap').FormGroup;
const Button = require('react-bootstrap').Button;
const AuthorisedLayout = require('./Layouts/loggedin');
class Generate extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
console.log('handleSubmit() clicked');
console.log(event);
event.preventDefault();
}
render() {
return (
<AuthorisedLayout title={this.props.title}>
<Jumbotron>
<Container>
<h1 className="display-3">{this.props.title}</h1>
<p>{this.props.username}, this will generate a new key pair to be stored on the server.</p>
<p>When the generation is complete, a zip file containing the key pair will download to your machine.</p>
</Container>
</Jumbotron>
<Container>
<Form onSubmit={this.handleSubmit}>
<FormGroup controlId="service">
<Form.Label>Service Name</Form.Label>
<Form.Control type="text" placeholder="Service name" value={this.state.value} onChange={this.handleChange}></Form.Control>
</FormGroup>
<Button variant="primary" type="submit">
Generate key pair
</Button>
</Form>
</Container>
</AuthorisedLayout>
);
}
}
module.exports = Generate;
我相信我的 express 应用已正确设置为使用 jsx 视图:
const app = express();
app.set('Views', __dirname + '/Views');
app.set('view engine', 'jsx');
app.engine('jsx', require('express-react-views').createEngine());
那么我怎样才能让我的 onSubmit 正常工作,它应该在哪里输出我拥有的各种 console.logs,并防止事件链发生?
编辑
我在这里创建了类似代码笔的东西:codepen
** 编辑 2** 只需更正代码以更好地查看
【问题讨论】:
-
您可以添加任何代码笔吗?
标签: node.js reactjs express bootstrap-4 react-bootstrap