我正在使用两个组件并且我正在使用这种模式:子组件应该尽可能地保持隔离 - 它正在处理自己的验证错误。父组件应检查子组件之间存在依赖关系的错误。所以,就我而言:password
字段和password confirmation
字段。
这是我的代码:
a) 注册(父母)
设置初始状态。
constructor() {
super();
this.state = {
isPasswordMatching: false
};
}
在render()
方法中,我正在输出我的子组件。通过 prop 调用callback
我正在isPasswordMatching()
通过绑定 parent 的this
. 目标是可以在子组件中调用该方法。
<TextInput
id={'password'}
ref={(ref) => this.password = ref}
callback={this.isPasswordMatching.bind(this)}
// some other unimportant props
/>
<TextInput
id={'passwordConfirm'}
ref={(ref) => this.passwordConfirm = ref}
...
isPasswordMatching()
方法是检查密码是否匹配(通过 refsthis.password
和this.passwordConfirm
),然后更新状态。请注意,此方法在子项内部调用(密码或密码确认)。
isPasswordMatching() {
this.setState({
isPasswordMatching: this.password.state.value === this.passwordConfirm.state.value
});
}
b) 文本输入(子)
设置初始状态。
constructor() {
super();
this.state = {
value: '',
isValid: false
};
}
完成模糊验证并更新状态。
onBlur(event) {
// doing validation and preparing error messages
this.setState({
value: value,
isValid: this.error === null
});
}
最新的。回调道具被调用。
componentDidUpdate(prevProps) {
if (prevProps.id === 'password' || prevProps.id === 'passwordConfirm') {
prevProps.callback();
}
}
问题
不知何故,我的裁判丢失了。设想:
- 父组件是渲染器
- 子组件被渲染
- 我正在输入一个输入字段并退出(这会调用
onBlur()
方法) - 状态得到更新,子组件被渲染 componentDidUpdate()
被调用,prevProp.callback()
以及- 当使用
isPasswordMatching()
我正在输出的方法时this.password
,this.passwordConfirm
它们是具有预期参考值的对象。更新父组件的状态 - 组件被渲染。 this.password
然后再次渲染所有子项,更新组件,调用回调,但这次this.passwordConfirm
是null
。
我不知道为什么参考文献有点丢失。我应该做一些不同的事情吗?先感谢您。