Files
freeCodeCamp/guide/chinese/certifications/front-end-libraries/react/create-a-controlled-form/index.md
Randell Dawson 0a1eeea424 fix(guide) Replace invalid prism code block names (#35961)
* fix: replace sh with shell

fix replace terminal with shell

fix replace node with js

fix replace output with shell

fix replace cs with csharp

fix replace c++ with cpp

fix replace c# with csharp

fix replace javasctipt with js

fix replace syntax  with js

fix replace unix with shell

fix replace linux with shell

fix replace java 8 with java

fix replace swift4 with swift

fix replace react.js with jsx

fix replace javascriot with js

fix replace javacsript with js

fix replace c++ -  with cpp

fix: corrected various typos

fix: replace Algorithm with nothing

fix: replace xaml with xml

fix: replace solidity with nothing

fix: replace c++ with cpp

fix: replace txt with shell

fix: replace code with json and css

fix: replace console with shell
2019-05-15 19:08:19 +02:00

1.4 KiB
Raw Blame History

title, localeTitle
title localeTitle
Create a Controlled Form 创建受控表格

创建受控表格

创建受控表单与创建受控输入的过程相同,除非您需要处理提交事件。

首先,创建一个受控输入,将其值存储在状态中,以便存在单一的事实来源。 这是您在上一次挑战中所做的。创建一个输入元素将其value属性设置为位于state中的输入变量。请记住 this.state可以访问状态。接下来设置input元素的onChange属性以调用函数'handleChange'。

<input value={this.state.input} onChange={this.handleChange}/> 

接下来为组件创建handleSubmit方法。首先因为您的表单正在提交您必须阻止页面刷新。其次调用setState()方法传入要更改的不同键值对的对象。在这种情况下您希望将“submit”设置为变量“input”的值并将“input”设置为空字符串。

handleSubmit(event) { 
  event.preventDefault(); 
  this.setState({ 
    input: '', 
    submit: this.state.input 
  }); 
 } 

现在您的数据正在处理状态,我们可以使用这些数据。创建一个h1元素。你的h1元素里面放了你的'submit'变量。请记住,'submit'位于州内,因此您需要使用this.state 。此外将变量放在JSX中需要花括号{ }因为它是JavaScript。

<h1>{this.state.submit}</h1>