state
作为道具传递给子组件,但您不仅限于传递数据。您还可以将处理函数或在React组件上定义的任何方法传递给子组件。这是允许子组件与其父组件交互的方式。您可以将方法传递给孩子,就像常规道具一样。它被分配了一个名称,您可以在子组件中的this.props
下访问该方法名称。 MyApp
组件是将呈现GetInput
和RenderInput
子组件的父组件。将GetInput
组件添加到MyApp
的render方法,然后从MyApp
的state
向它传递一个名为input
的prop,该input
分配给inputValue
。还要创建一个名为handleChange
的prop,并将输入处理程序handleChange
给它。接下来,将RenderInput
添加到MyApp
的render方法,然后创建一个名为input
的prop,并将inputValue
从state
传递给它。完成后,您将能够在GetInput
组件中input
字段,然后通过props调用其父级中的处理程序方法。这将更新父级state
的输入,该输入作为props传递给两个子级。观察数据如何在组件之间流动以及单个事实源如何保持父组件的state
。不可否认,这个例子有点人为,但应该用来说明如何在React组件之间传递数据和回调。 MyApp
组件应该呈现。
testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyApp)); return mockedComponent.find("MyApp").length === 1; })(), "The MyApp
component should render.");'
- text: GetInput
组件应该呈现。
testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyApp)); return mockedComponent.find("GetInput").length === 1; })(), "The GetInput
component should render.");'
- text: RenderInput
组件应该呈现。
testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyApp)); return mockedComponent.find("RenderInput").length === 1; })(), "The RenderInput
component should render.");'
- text: GetInput
组件应该将MyApp
状态属性inputValue
作为props接收,并包含一个修改MyApp
状态的input
元素。
testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyApp)); const state_1 = () => { mockedComponent.setState({inputValue: ""}); return waitForIt(() => mockedComponent.state() )}; const state_2 = () => { mockedComponent.find("input").simulate("change", {target: {value: "TestInput"}}); return waitForIt(() => mockedComponent.state() )}; const updated_1 = await state_1(); const updated_2 = await state_2(); assert(updated_1.inputValue === "" && updated_2.inputValue === "TestInput", "The GetInput
component should receive the MyApp
state property inputValue
as props and contain an input
element which modifies MyApp
state."); }; '
- text: RenderInput
组件应该将MyApp
状态属性inputValue
作为props接收。
testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyApp)); const state_1 = () => { mockedComponent.setState({inputValue: "TestName"}); return waitForIt(() => mockedComponent )}; const updated_1 = await state_1(); assert(updated_1.find("p").text().includes("TestName"), "The RenderInput
component should receive the MyApp
state property inputValue
as props."); }; '
```
{this.props.input}