我是ReactJ的新手。所以,我不知道,我在这里做错了什么。因此,我有一个父组件,该组件具有形式和一个子组件。父组件的表单和子组件的一些字段几乎没有字段。子组件的状态是在父组件中定义的,并将其作为道具传递给它。因此,在儿童组件中,我有电子邮件,密码,确认密码字段和提交按钮。在这里,我需要实现的是,当用户给密码的值相同的值并确认密码字段时,提交按钮将启用。如果他给出了不同的值,则应禁用提交按钮。请看一下我的代码以清楚地理解它。
预先感谢
import React, { Component } from 'react';
import FormPartTwo from './FormPartTwo';
class Form extends Component {
constructor(props){
super(props);
this.state = {
FirstName: "",
LastName: "",
Email: "",
Password: "",
ConfirmPassword: ""
}
}
handleChange = e =>{
this.setState({
[e.target.name]: e.target.value
})
}
handleClick = e => {
e.preventDefault();
console.log(this.state);
}
render() {
return (
<div>
<input
type = "text"
name = "FirstName"
placeholder="First Name"
value = {this.state.FirstName}
onChange = {this.handleChange}
/>
<input
type = "text"
name = "LastName"
placeholder="Last Name"
value = {this.state.LastName}
onChange = {this.handleChange}
/>
<FormPartTwo handleClick={this.handleClick} doChange={this.handleChange} {...this.props}/>
</div>
)
}
}
export default Form
/---Component Two---/
import React, { Component } from 'react'
class FormPartTwo extends Component {
render() {
return (
<div>
<input
type="email"
name="Email"
value={this.props.Email}
placeholder="Email"
onChange={this.props.doChange}
/>
<input
type="password"
name="Password"
placeholder="Password"
value={this.props.Password}
onChange={this.props.doChange}
/>
<input
type="password"
name="ConfirmPassword"
placeholder="Retype Password"
value={this.props.ConfirmPassword}
onChange={this.props.doChange}
/>
<input
type="submit"
disabled = {this.props.Password ==! this.props.ConfirmPassword}
onClick={e => this.props.handleClick(e)}
/>
</div>
)
}
}
export default FormPartTwo
问题是您使用的是在FormPartTwo
组件中使用输入值(例如this.props.password,this.props.confirmpassword,...(,而无需实际将它们传递到组件中。<FormPartTwo handleClick={this.handleClick} doChange={this.handleChange} {...this.props}/>
。
您应该做的是将此值传递到Prop中的FormPartTwo
组件中。
// Form.js
<FormPartTwo
{...this.props}
handleClick={this.handleClick}
doChange={this.handleChange}
{...this.state}
/>
然后在FormPartTwo
组件中您可以创建检查变量是否应禁用提交按钮。
// FormPartTwo.js
render () {
const isSubmitDisabled =
!this.props.Password ||
!this.props.ConfirmPassword ||
this.props.Password !== this.props.ConfirmPassword;
return (
...
<input
type="submit"
disabled={isSubmitDisabled}
onClick={e => this.props.handleClick(e)}
/>
...
)
}
这是工作示例的链接。希望这会有所帮助!