假设我有一个工具提示组件,它根据是否有文本数据来显示和隐藏:
{this.state.tooltipText && (
<Tooltip
text={this.state.tooltipText} />
)}
如果我想将此组件转入和转出,我可能会包含一个 bool 值 on
属性,并让组件自行管理转出。
<Tooltip
on={this.state.tooltipText !== null}
text={this.state.tooltipText} />
但是,通过此设置,当转换开始时,我丢失了 text
属性。很明显,永远不会有 on
为 false
的状态,而且我仍然可以访问 text
属性。
有没有好的方法来处理这种情况?
- 组件是否应该保留
tooltipText
先前状态的内部记录? - 或者最好使用两个属性来跟踪工具提示的状态(
tooltipOn
和tooltipText
),并且永远不要删除this.state.tooltipText
?
最佳答案
Should the component keep an internal record of the previous state of tooltipText?
是的。否则,家长必须决定过渡何时开始/结束,这不是他的权力。
实际上 componentWillReceiveProps
最适合这种情况,因为您可以访问当前和下一个属性:
componentWillReceiveProps(nextProps) {
if(this.props.text && !nextProps.text) {
this.fadeOut();
} else if(!this.props.text && nextProps.text) {
this.setState({ text: nextProps.text });
this.fadeIn();
}
}
然后父级就有:
<Tooltip text={this.state.tooltipText} />
关于javascript - 在卸载之前对已丢失其需要显示的 props 数据的 React 组件进行动画处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52709971/