获取其他组件React.js的价值

时间:2019-07-29 04:52:42

标签: reactjs

我的Login.js中有此代码:

<div className="row justify-content-start">
                <form className="form-signin">
                    <PageDetailsHeading name="Please Log-In to continue"/>
                    <EmailField/>
                    <PasswordField/>
                    <ButtonActor name="Log In" isPrimaryButton="true"/>
                </form>
            </div>

当我按EmailField时如何获得ButtonActor的值?

这是我的EmailField.js

<div className="form-label-group">
                <input type="email" id="inputEmail" className="form-control" placeholder="Email address" required autoFocus onKeyDown={this._handleKeyDown}/>
                <label htmlFor="inputEmail">Email address</label>
            </div>

2 个答案:

答案 0 :(得分:1)

您只需要维护Login组件中的状态,

state={email:''}

您还需要仅在onChange组件中拥有onClick处理程序和Login,并将它们分别传递到EmailFieldButtonActor

onEmailChange = (e) =>{
  this.setState({[e.target.name]:e.target.value})
}

onButtonClick = () =>{
   console.log(this.state.email)
}

将函数传递给组件

<EmailField onEmailChange={this.onEmailChange}/>
<ButtonActor name="Log In" isPrimaryButton="true" onButtonClick={this.onButtonClick}/>

EmailField组件,

<div className="form-label-group">
   <input type="email" id="inputEmail" className="form-control" placeholder="Email address" required autoFocus onChange={this.props.onEmailChange} name="email"/> //notice attribute `name`
   <label htmlFor="inputEmail">Email address</label>
</div>

ButtonActor组件,

<button onClick={this.props.onButtonClick}>Log In</button>

答案 1 :(得分:0)

您可以通过在组件状态中提及来实现这一点。