我有一个带有提交按钮的表单。该表单调用一个onclick函数,该函数将某物的状态从false设置为true。然后,我想将此状态传递回父级,这样,如果为true,则呈现componentA;如果为false,则呈现componentB。
我会如何反应?我知道我需要使用状态或道具,但不确定如何使用它。这也与单向流动反应原理矛盾吗?
ComponentA代码:
<form onSubmit={this.handleClick}> handleClick(event) { this.setState({ decisionPage: true }); event.preventDefault(); };
控制其显示内容的父组件:
return ( <div> {this.props.decisionPage ? <div> <LoginPage /> </div> : <div> <Decision showThanks={this.props.showThanks}/> </div> } </div> )
移动handleClick到父级并将其作为道具传递给子级组件。
handleClick
<LoginPage handleClick={this.handleClick.bind(this)}/>
现在在子组件中:
<form onSubmit={this.props.handleClick}>
这样,提交表单将直接更新父组件中的状态。这假设您不需要访问子组件中的更新状态值。如果这样做,则可以将状态值作为道具从父级传递回子级。保持单向数据流。
<LoginPage handleClick={this.handleClick.bind(this)} decisionPage={this.state.decisionPage}/>