我正在使用两个组件并采用以下模式: 子组件应尽可能保持隔离 - 它处理自己的验证错误。父组件应检查存在子组件之间依赖的错误。因此,在我的情况下: 密码
字段和 确认密码
字段。
这是我的代码:
a) 注册 (父组件)
设置初始状态。
constructor() {
super();
this.state = {
isPasswordMatching: false
};
}
在render()
方法中,我输出了我的子组件。通过名为callback
的属性,我通过绑定父组件的this
来传播isPasswordMatching()
方法。目标是使该方法可以在子组件中被调用。<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()
方法检查密码是否匹配(通过引用 this.password
和 this.passwordConfirm
),然后更新状态。请注意,此方法在子组件 (password 或 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
。
我不知道为什么引用会丢失。我应该做些什么不同的事情吗? 提前感谢。
ref
元素,则需要使用style={{ display: 'none' }}
而不是简单地不渲染它,否则将不会创建引用。 - Raine Revere