--- id: 5a24c314108439a4d4036178 title: Create a Controlled Input challengeType: 6 isRequired: false videoUrl: '' localeTitle: 创建受控输入 --- ## Description
您的应用程序可能在state和呈现的UI之间进行更复杂的交互。例如,用于文本输入的表单控件元素(例如inputtextarea在用户键入时在DOM中维护它们自己的状态。使用React,您可以将此可变状态移动到React组件的state 。用户的输入成为应用程序state一部分,因此React控制该输入字段的值。通常,如果React组件具有用户可以键入的输入字段,则它将是受控输入表单。
## Instructions
代码编辑器具有名为ControlledInput的组件的骨架,以创建受控input元素。组件的state已经使用包含空字符串的input属性进行初始化。此值表示用户在input字段中键入的文本。首先,创建一个名为handleChange()的方法,该方法具有一个名为event的参数。调用该方法时,它会接收一个event对象,该对象包含input元素中的一串文本。您可以使用方法内的event.target.value访问此字符串。使用此新字符串更新组件stateinput属性。在render方法中,在h4标记上方创建input元素。添加一个value属性,该属性等于组件stateinput属性。然后将onChange()事件处理程序集添加到handleChange()方法。当您在输入框中键入时,该文本由handleChange()方法处理,设置为本地stateinput属性,并在页面的input框中呈现为值。组件state是关于输入数据的单一事实来源。最后但并非最不重要的是,不要忘记在构造函数中添加必要的绑定。
## Tests
```yml tests: - text: ControlledInput应返回包含inputp标记的div元素。 testString: 'assert(Enzyme.mount(React.createElement(ControlledInput)).find("div").children().find("input").length === 1 && Enzyme.mount(React.createElement(ControlledInput)).find("div").children().find("p").length === 1, "ControlledInput should return a div element which contains an input and a p tag.");' - text: ControlledInput的状态应该初始化, input属性设置为空字符串。 testString: 'assert.strictEqual(Enzyme.mount(React.createElement(ControlledInput)).state("input"), "", "The state of ControlledInput should initialize with an input property set to an empty string.");' - text: 输入input元素应更新输入的状态和值, p元素应在键入时呈现此状态。 testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(ControlledInput)); const _1 = () => { mockedComponent.setState({ input: "" }); return waitForIt(() => mockedComponent.state("input"))}; const _2 = () => { mockedComponent.find("input").simulate("change", { target: { value: "TestInput" }}); return waitForIt(() => ({ state: mockedComponent.state("input"), text: mockedComponent.find("p").text(), inputVal: mockedComponent.find("input").props().value }))}; const before = await _1(); const after = await _2(); assert(before === "" && after.state === "TestInput" && after.text === "TestInput" && after.inputVal === "TestInput", "Typing in the input element should update the state and the value of the input, and the p element should render this state as you type."); }; ' ```
## Challenge Seed
```jsx class ControlledInput extends React.Component { constructor(props) { super(props); this.state = { input: " }; // change code below this line // change code above this line } // change code below this line // change code above this line render() { return (
{ /* change code below this line */} { /* change code above this line */}

Controlled Input:

{this.state.input}

); } }; ```
### After Test
```js console.info('after the test'); ```
## Solution
```js // solution required ```