[英]How can a stateless component prop function run when it renders?
I have a long list of items and when they render, I want the scroll to move to the bottom of the list -- but only when they render. 我有一长串项目,当他们渲染时,我希望滚动移动到列表的底部 - 但只有当它们渲染时。 Does anyone know how to do this with a stateless component?
有没有人知道如何使用无状态组件执行此操作? I would like a function to run as a prop on the component and I want this function to pass the element so that in my container component with the Redux API I can scroll to the element.
我想要一个函数作为组件的prop运行,我希望这个函数传递元素,以便在我的容器组件中使用Redux API我可以滚动到该元素。 However, I only want the function to run when the component renders, and I am struggling to get a function on a component to run when it renders with itself passed as an argument.
但是,我只希望函数在组件呈现时运行,并且我很难在组件上运行时获取一个函数,当它以自身的形式作为参数传递时。
I am familiar with these events in a class component regarding the lifecycle of a component: 我熟悉关于组件生命周期的类组件中的这些事件:
But these lifecycle events are not available to me in a stateless component. 但是这些生命周期事件在无状态组件中是不可用的。
Stateless function components do not have a lifecycle as that would be nonsensical. 无状态功能组件没有生命周期,因为它是荒谬的。 The React lifecycle is inherently stateful.
React生命周期本质上是有状态的。
You've got a few options: 你有几个选择:
recompose
and the lifecycle
higher order component it provides. recompose
和它提供的lifecycle
高阶组件。 Based on your last comment, you could solve your use case like this: https://jsfiddle.net/69z2wepo/83446/ 根据您的上一条评论,您可以像这样解决您的用例: https : //jsfiddle.net/69z2wepo/83446/
In the list component, you add this in the componentWillMount: 在list组件中,您可以在componentWillMount中添加它:
componentWillReceiveProps(newProps) {
if (!this.props.comments.length && newProps.comments.length) {
// Using setTimeout 0 will cause the function to be triggered after the re-render
setTimeout(() => {
// this.list being a ref on the list component
const { height } = this.list.getBoundingClientRect();
document.body.scrollTop = height;
}, 0);
}
}
In this case the Comment component can be stateless 在这种情况下,Comment组件可以是无状态的
function Comment(props) {
return (
<li>{props.comment.content}</li>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.