我正在使用两个组件,我正在使用这种模式:子组件应尽可能保持隔离 - 它正在处理自己的验证错误.父组件应检查具有子项之间依赖关系的错误.所以,在我的情况下:password
字段和password confirmation
字段.
这是我的代码:
a)SignUp(父母)
设置初始状态.
constructor() {
super();
this.state = {
isPasswordMatching: false
};
}
Run Code Online (Sandbox Code Playgroud)
在render()
方法中,我输出了我的子组件.通过道具称为callback
我isPasswordMatching()
通过绑定父母的传播方法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}
...
Run Code Online (Sandbox Code Playgroud)
isPasswordMatching()
方法是检查密码是否匹配(通过refs this.password
和this.passwordConfirm
)然后更新状态.请注意,此方法在child(password或passwordConfirm)内部调用.
isPasswordMatching() {
this.setState({
isPasswordMatching: this.password.state.value === this.passwordConfirm.state.value
});
}
Run Code Online (Sandbox Code Playgroud)
b)TextInput(孩子)
设置初始状态.
constructor() {
super();
this.state = {
value: '',
isValid: false
};
}
Run Code Online (Sandbox Code Playgroud)
在模糊验证完成并更新状态.
onBlur(event) {
// doing validation and preparing error messages
this.setState({
value: value,
isValid: this.error === null
});
}
Run Code Online (Sandbox Code Playgroud)
最新.调用回调道具.
componentDidUpdate(prevProps) {
if (prevProps.id === 'password' || prevProps.id === 'passwordConfirm') {
prevProps.callback();
}
}
Run Code Online (Sandbox Code Playgroud)
问题
不知何故,我的裁判丢失了.场景:
onBlur()
方法) - 状态得到更新,子组件被渲染componentDidUpdate()
被调用,prevProp.callback()
以及isPasswordMatching()
方法,我输出this.password
和this.passwordConfirm
-它们与基准预期值的对象.更新父级的状态 - 组件被渲染.this.password
与this.passwordConfirm
是null
.我不知道为什么引用有点丢失.我应该采取不同的做法吗?先感谢您.
Gal*_*sha 15
请参阅此处的反应文档,其中包含重要警告,并建议何时使用或不使用refs.
请注意,当卸载引用的组件时,每当ref更改时,将使用null作为参数调用旧的ref.这可以防止在存储实例的情况下发生内存泄漏,如第二个示例中所示.还要注意,当使用内联函数表达式编写refs时,如此处的示例中所示,每次更新时,React都会看到不同的函数对象,在使用组件实例调用ref之前,ref将立即调用null.
我不确定这是否能回答@ be-codified的问题,但是我发现这也遇到了类似的问题。就我而言,事实证明,这是由于使用功能组件。
https://reactjs.org/docs/refs-and-the-dom.html#refs-and-functional-components
引用和功能组件不能在功能组件上使用ref属性,因为它们不需要。如果需要引用,则应将组件转换为类,就像需要生命周期方法或状态时一样。
但是,只要引用DOM元素或类组件,就可以在功能组件内使用ref属性。
该文档解释了你应该做的,如果你有你想呈现组件的控制来解决这个问题。
然而,在我的情况下,该组件是从一个第三方库。因此,仅包装组件即可正常工作。
工作中
<div ref={element => this.elementName = element}>
<FunctionalComponent />
</div>
Run Code Online (Sandbox Code Playgroud)
不工作
将this.elementName设置为null
<FunctionalComponent ref={element => this.elementName = element} />
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助任何人像我一样找到这个问题。
归档时间: |
|
查看次数: |
12997 次 |
最近记录: |