state
和呈现的UI之间进行更复杂的交互。例如,用于文本输入的表单控件元素(例如input
和textarea
在用户键入时在DOM中维护它们自己的状态。使用React,您可以将此可变状态移动到React组件的state
。用户的输入成为应用程序state
一部分,因此React控制该输入字段的值。通常,如果React组件具有用户可以键入的输入字段,则它将是受控输入表单。 ControlledInput
的组件的骨架,以创建受控input
元素。组件的state
已经使用包含空字符串的input
属性进行初始化。此值表示用户在input
字段中键入的文本。首先,创建一个名为handleChange()
的方法,该方法具有一个名为event
的参数。调用该方法时,它会接收一个event
对象,该对象包含input
元素中的一串文本。您可以使用方法内的event.target.value
访问此字符串。使用此新字符串更新组件state
的input
属性。在render方法中,在h4
标记上方创建input
元素。添加一个value
属性,该属性等于组件state
的input
属性。然后将onChange()
事件处理程序集添加到handleChange()
方法。当您在输入框中键入时,该文本由handleChange()
方法处理,设置为本地state
的input
属性,并在页面的input
框中呈现为值。组件state
是关于输入数据的单一事实来源。最后但并非最不重要的是,不要忘记在构造函数中添加必要的绑定。 ControlledInput
应返回包含input
和p
标记的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."); }; '
```
{this.state.input}