亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我想在我的路由組件中添加一個表單元素

我想在我的路由組件中添加一個表單元素

料青山看我應如是 2021-11-12 18:22:05
我是新來的,我有這個路由組件,在這個里面我正在創建我的新數據的每一行的元素,但我也想添加表單,以便用戶可以創建一個新的段落。有人可以幫我嗎??import React, { Component } from 'react';import axios from 'axios';class Comments extends Component {state={    Comment:[]}componentDidMount() {    const { commentId }=this.props.location.state;    axios.get(`./hn_data/${commentId}.json`)        .then((res) => this.setState({ Comment: res.data }));}render() {    console.log(this.state.Comment);    return this.state.Comment.map(comment=>(        <p>{comment.text}</p>    ))}}export default Comments;`
查看完整描述

1 回答

?
慕桂英546537

TA貢獻1848條經驗 獲得超10個贊

就我所知,您想添加一個用于提交新評論的表單,請寫信?


嘗試這個:


import React, { Component } from 'react';


import axios from 'axios';


class Comments extends Component {

    state = {

        Comment: [],

        commentText: "",

    };


    componentDidMount() {

        const { commentId } = this.props.location.state;


        axios.get(`./hn_data/${commentId}.json`)

            .then((res) => this.setState({ Comment: res.data }));

    }


    postComment() {

        // add you comment to the database here

    }


    onCommentTextChange(event) {

        this.setState({

            commentText: event.currentTarget.value,

        });

    }


    renderComments() {

        return this.state.Comment.map(comment=>(

            <p>{comment.text}</p>

        ));

    }


    renderForm() {

        return (

            <div class="comment-form">

                <textarea

                    class="comment-form__text" 

                    value={this.state.newCommentText}

                    onChange={(event) => this.onCommentTextChange(event)}

                ></textarea>

                <button onClick={() => this.postComment()}>Submit</button>

            </div>

        )

    }


    render() {


        console.log(this.state.Comment);


        return (

            <div>

                {this.renderComments()}

                {this.renderForm()}

            </div>

        )

    }

}


export default Comments;

在 postComment 中,您可以將 this.state.commentText 添加到 state.Comment 中或發布到后端。


查看完整回答
反對 回復 2021-11-12
  • 1 回答
  • 0 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號