反应不是触发形式onSubmit函数

时间:2019-06-16 01:37:54

标签: reactjs

我正在尝试提交onSubmit表单,但没有触发this.commentSubmit函数,如果我将<form></form>取出,请使用<Button onSubmit>函数,但是我需要包裹在Textfield周围的表单,供后端读取req.body.comment_body来工作。

Comment.js

import React  from "react";
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
const Comment = (props) => (
    <form onSubmit={props.onSubmit}>
        <TextField
            type="text"
            id="outlined-multiline-static"
            label="Write A Comment"
            multiline
            name="comment_body"
            value={props.commentBody}
            rows="10"
            fullWidth
            margin="normal"
            variant="outlined"
            onChange={props.commentChange}
        />
        <Button type="submit" variant="outlined" component="span" color="primary">
            Post A Comment
        </Button>
    </form>

)
export default Comment;

图像容器组件

import React from "react";
import Button from '@material-ui/core/Button';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import Divider from '@material-ui/core/Divider';
import Image from './Image';
import Axios from '../Axios';
import moment from 'moment';
import Comment from './Comment';

class ImageContainer extends React.Component{
    state = {
      isComment: false,
      comment_body: ""
    }

    handleCommentChange = (e) => {
        this.setState({
           comment_body: e.target.value
        })             
    }

    writeComment = (id)  => {
        this.setState({
            isComment: this.state.isComment ? '' : id // check if you state is filled to toggle on/off comment
        })   
    }

    commentSubmit = (e) => {
        e.preventDefault();
        console.log(this.state.comment_body); // doesn't get console.log
        Axios.post('/images/newComment', this.state.comment_body).then( (response )=> {
            const newComment = { ...response.data};
            console.log(newComment);
            this.setState({
                comment_body: ''
            })
        })
    }

    render(){
       const { img, deleteImg } = this.props
       return(
           <Grid item sm={12} md={12} style={{ margin: '30px 0px'}}>
               <Paper style={{padding:'20px 20px'}}>
         {/* // empty image_title */}
               <Typography style={{ padding: '30px 5px', letterSpacing:'8px', textTransform:'uppercase'}} variant="h4" align="center">{img.image_title}</Typography> 
               <Divider style={{ width: '150px', margin:'10px auto', backgroundColor:'#000000'}} variant="middle" />
               <Image image_url={img.img_url} />   
               <Typography variant="h6" align="center">{img.user.username}</Typography> 
               <Typography variant="h6" align="center">{moment(img.created_at).calendar()}</Typography> 
               <Button onClick ={() => this.writeComment(img.id)} variant="outlined" component="span" color="primary"> 
            {this.state.isComment === img.id ? "Close" : "Write A Comment"}
               </Button>
            {/* here were prevent comments being selected for all items in the array, renders the comment form you clicked on.  */}
            {this.state.isComment === img.id ?
               <Comment onSubmit={this.commentSubmit} 
                            commentBody={this.state.comment_body } 
                            commentChange={this.handleCommentChange}/> 
            : null}
            {/* hide delete button when user enters comment */}
            {!this.state.isComment ? <Button style={{margin: '0px 20px'}} onClick={deleteImg} variant="outlined" component="span" color="primary">
                Delete
            </Button> : null}

            </Paper>                              
        </Grid>        
      )
   }
}

export default ImageContainer

或者这可行,但是我不认为后端读取comment_body值

import React  from "react";
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
const Comment = (props) => {
    // <form onSubmit={props.onSubmit}>

    return(
        <div>
        <TextField
            type="text"
            id="outlined-multiline-static"
            label="Write A Comment"
            multiline
            name="comment_body"
            value={props.commentBody}
            rows="10"
            fullWidth
            margin="normal"
            variant="outlined"
            onChange={props.commentChange}
        />
        <Button onClick={props.onSubmit} type="submit" variant="outlined" component="span" color="primary">
            Post A Comment
        </Button>
        </div>
    );
    // </form>

}
export default Comment;

后端

router.post('/newComment', async (req, res) => {
    const comment = new Comment({
        comment_body: req.body.comment_body,
        user_id: req.user.id
    })

    comment.save().then( (comment) => {
        return res.status(200).json(comment);
    })
})

1 个答案:

答案 0 :(得分:1)

问题在于Material-ui中的<Button>不是一个实际的按钮,而是<span>的组合。因此,如果您有type="submit",则该表格不会执行任何操作。

如果您将材料用户界面<Button>更改为本地<button>,它将按预期工作。

下面是一个示例:https://codesandbox.io/embed/56615445-fj6sc