Я создал компонент SignIn используя пример пользовательского интерфейса материала.
import React from 'react';
import PropTypes from 'prop-types';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import FormControl from '@material-ui/core/FormControl';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import Input from '@material-ui/core/Input';
import InputLabel from '@material-ui/core/InputLabel';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import withStyles from '@material-ui/core/styles/withStyles';
const styles = theme => ({
main: {
width: 'auto',
display: 'block', // Fix IE 11 issue.
marginLeft: theme.spacing.unit * 3,
marginRight: theme.spacing.unit * 3,
[theme.breakpoints.up(400 + theme.spacing.unit * 3 * 2)]: {
width: 400,
marginLeft: 'auto',
marginRight: 'auto',
},
},
paper: {
marginTop: theme.spacing.unit * 8,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
padding: `${theme.spacing.unit * 2}px ${theme.spacing.unit * 3}px ${theme.spacing.unit * 3}px`,
},
avatar: {
margin: theme.spacing.unit,
backgroundColor: theme.palette.secondary.main,
},
form: {
width: '100%', // Fix IE 11 issue.
marginTop: theme.spacing.unit,
},
submit: {
marginTop: theme.spacing.unit * 3,
},
});
function SignIn(props) {
const { classes } = props;
return (
<main className = {classes.main}>
<CssBaseline />
<Paper className = {classes.paper}>
<Avatar className = {classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component = "h1" variant = "h5">
Sign in
</Typography>
<form className = {classes.form}>
<FormControl margin = "normal" required fullWidth>
<InputLabel htmlFor = "email">Email Address</InputLabel>
<Input id = "email" name = "email" autoComplete = "email" autoFocus />
</FormControl>
<FormControl margin = "normal" required fullWidth>
<InputLabel htmlFor = "password">Password</InputLabel>
<Input name = "password" type = "password" id = "password" autoComplete = "current-password" />
</FormControl>
<FormControlLabel
control = {<Checkbox value = "remember" color = "primary" />}
label = "Remember me"
/>
<Button
type = "submit"
fullWidth
variant = "contained"
color = "primary"
className = {classes.submit}
>
Sign in
</Button>
</form>
</Paper>
</main>
);
}
SignIn.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(SignIn);
Теперь я хочу использовать его в родительском компоненте с обработчиком отправки. Но я не могу понять, как выполнить обработчик при отправке формы в дочернем компоненте
import React, { Component } from "react";
import SignIn from "../components/SignIn";
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit = async event => {
// Do Stuff
}
render() {
return (
<div className = "Login">
<SignIn onSubmit = {this.handleSubmit}/>
</div>
);
}
}
Можете ли вы уточнить, «как попасть в обработчик при отправке»? Что ты имеешь в виду?
@Nifled Код дочернего компонента буквально представляет собой код, на который я ссылаюсь в примере. Я отредактирую вопрос, чтобы все было на одной странице.
@KatiaWheeler Я хочу выполнить обработчик при отправке формы из дочернего компонента





Измените свою кнопку в компоненте SignIn, чтобы вызвать обработчик отправки, переданный через реквизит, следующим образом:
<Button
type = "submit"
fullWidth
variant = "contained"
color = "primary"
className = {classes.submit}
onClick = {this.props.onSubmit}
>
Sign in
</Button>
Это или вы можете добавить его на самой форме (для семантики). <form onSubmit = {this.props.onSubmit} ...>
Я был почти уверен, что пробовал это, но, видимо, я этого не делал. Спасибо, это работает, и я должен сделать перерыв ...! Если кому интересно, данные формы доступны в event.target в обработчике.
Я предлагаю вам также добавить код дочернего компонента. Со стороны родителя вроде все нормально.