首页 > 解决方案 > ReactJS passing input data to next screen/component

问题描述

I've looked up whole google for my answer (haha). What I am trying to achieve:

My fist screen is a form with some input fields which store the input to state. By clicking "submit" the user comes to the next page/screen, where the previous input is supposed to show up. I want to show only the input data as a p-tag, not as an input tag anymore.

How do I achieve this? I am bloody new to reactjs.

I've thought about multiple solutions:

  1. store the input data to an external JSON (which seems pretty complicated)
  2. pass the data as props, but I am not aware of how I would do this

Thanks so far!

标签: javascriptreactjsinput

解决方案


我将假设您的第二个屏幕与您的第一个屏幕具有相同的父组件,如下所示:

render() {
    return (
        <div>
            {this.state.showFirstScreen && <FirstScreen />}
            {this.state.showSecondcreen && <Secondcreen />}
        </div>
    )
}

如果是这种情况,您的FirstScreen组件可以接受一个称为类似的道具onSubmit- 您说您已经存储了FirstScreen状态中的输入值,所以当FirstScreen完成时,您可以调用this.props.onSubmit(this.state)并将状态发送到您的父组件,如只要你在父组件中定义了回调函数:

{this.state.showFirstScreen && <FirstScreen onSubmit={this.onFirstScreenSubmit} />}

然后,您可以将第一个屏幕的状态保存到父组件的状态中,并将该部分状态传递给SecondScreen

[编辑] 这是一个非常粗略的例子:https ://jsfiddle.net/df4s9ey8/


推荐阅读