首页 > 解决方案 > 表单在 ReactJs 中是如何工作的?

问题描述

有人可以告诉我表单在 ReactJS 中是如何工作的吗?

当用户单击提交按钮时,我从反应文档中看到的表单下的数据如何显示,关于表单少指导我

例如以非常简单的方式我如何在单击提交按钮时显示数据检查示例。在表单底部显示数据,当输入任何文本然后单击提交按钮然后显示我在表单下方输入文本,我该怎么做?

import React,{Component} from 'react'
class FormHandling extends Component{
    constructor(props){
        super(props)
        this.state={text:''}
        this.handleChange = this.handleChange.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this)
    }
    handleChange(e){
        this.setState({
            text:e.target.value
        })
    }
    handleSubmit(e){
        e.preventDefault()
        // what i can write ther 
    }
    render(){
        return(
            <div>
                <form onSubmit={this.handleSubmit} >
                    <input type="text" onChange={this.handleChange} value={this.state.text} placeholder="enter name"  />
                    <input type="submit" value="Submit"   />
                </form>
            </div>
        )
    }

}

export default FormHandling

标签: reactjsforms

解决方案


handleSubmit(e){
  e.preventDefault()
  // 1st -> send code to an api
  fetch('some_url', {
    headers: {   
     'Accept': 'application/json',
     'Content-Type': 'application/json'
    },
    method: "POST",
    body: JSON.stringify(this.state.text)
   })
  .then(function(res){ console.log(res) })
  .catch(function(res){ console.log(res) });
 }
}
// 2 -> flag

state = {
 text: '',
 flag: false
}
handleSubmit = e => {
 e.preventDefault();
 this.setState({flag: true});
}
...
return(
 <div>
   <Form onSubmit={this.handleSubmit}/>
   {flag && <OtherComp textFromForm={this.state.text} /> } 
   // or something like this. (if flag is true then render comp) 
   // I didn't proof this but this is the idea of what you'd do.
 </div>
)




推荐阅读