延迟渲染React组件 [英] Delayed rendering of React components
问题描述
我有一个包含许多子组件的React组件。我希望不是一次渲染子组件,而是在延迟一段时间后(每个孩子都统一或不同)。
我想知道 - 有没有办法如何这样做?
我认为最直观的方法是让孩子们等待 prop
,它隐藏了从父节点传递的持续时间的组件。通过将默认状态设置为隐藏,React仍将立即呈现组件,但在状态发生更改之前它将不可见。然后,你可以在<$ p
< p $ p> var Child = React.createClass({
getInitialState:function(){
return({hidden:hidden});
},
componentWillMount:function(){
var that = this;
setTimeout(function(){
that.show();
},that.props.wait) ;
},
show:function(){
this.setState({hidden:});
},
render:function(){
返回(
< div className = {this.state.hidden}>
< p> Child< / p>
< / div>
)
}
});
然后,在Parent组件中,您需要做的只是传递您想要一个孩子的持续时间在显示之前等待。
var Parent = React.createClass({
render:function(){
返回(
< div className =parent>
< p> Parent< / p>
< div className =child-list>
<儿童等待= {1000} />
<儿童等待= {3000} />
<儿童等待= {5000} />
< / div> ;
< / div>
)
}
});
I have a React component with a number of child components in it. I want to render the child components not at once but after some delay (uniform or different for each of the children).
I was wondering - is there a way how to do this?
I think the most intuitive way to do this is by giving the children a "wait" prop
, which hides the component for the duration that was passed down from the parent. By setting the default state to hidden, React will still render the component immediately, but it won't be visible until the state has changed. Then, you can set up componentWillMount
to call a function to show it after the duration that was passed via props.
var Child = React.createClass({
getInitialState : function () {
return({hidden : "hidden"});
},
componentWillMount : function () {
var that = this;
setTimeout(function() {
that.show();
}, that.props.wait);
},
show : function () {
this.setState({hidden : ""});
},
render : function () {
return (
<div className={this.state.hidden}>
<p>Child</p>
</div>
)
}
});
Then, in the Parent component, all you would need to do is pass the duration you want a Child to wait before displaying it.
var Parent = React.createClass({
render : function () {
return (
<div className="parent">
<p>Parent</p>
<div className="child-list">
<Child wait={1000} />
<Child wait={3000} />
<Child wait={5000} />
</div>
</div>
)
}
});
这篇关于延迟渲染React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!