reactjs - 如何正确初始化 React 中的函数?
问题描述
请告诉我,如何正确解决以下问题?我有某个组件,上面有一个控件,当我点击它时,触发了setState。我需要调用函数 this.setScrollLeft () ,在该函数中我设置为所选节点(参考),在这种情况下为劈裂位置。这是我的实现,但我确信有更好的解决方案:
import React from 'react';
import { ScoreCell, getScoreTheme } from 'components/scores';
class LeaderboardPlayerResult extends React.Component {
constructor(props) {
super(props);
this.containerWidth = 198;
this.data = this.props.data;
this.playerResultRef = React.createRef();
}
componentDidMount() {
this.element = this.playerResultRef.current;
this.element.scrollLeft = this.containerWidth;
}
setScrollLeft = () => {
if (this.element) {
this.element.scrollLeft = this.containerWidth;
}
};
playerResult = () => {
if (this.data.playOffHoles) {
return (
this.data.playOffHoles.map((item, index) => {
return (
<div
className="leaderboard__player-result-row-wrapper"
key={index}
>
<div className="leaderboard__player-result-row">
<div className="leaderboard__player-result-cell">{item.holeId}</div>
</div>
<div className="leaderboard__player-result-row">
<div className="leaderboard__player-result-cell">{item.holePar}</div>
</div>
<div className="leaderboard__player-result-row">
<div className="leaderboard__player-result-cell leaderboard__player-result-cell--score">
<ScoreCell
childCss='tee-times-card__score'
theme={getScoreTheme(item.playOffParScore)}
>{item.playOffParScore}</ScoreCell>
</div>
</div>
</div>
);
})
);
}
};
render() {
console.log('LeaderboardPlayerResult render');
this.setScrollLeft();
return (
<div
className="leaderboard__player-result"
ref={this.playerResultRef}
>
{this.playerResult()}
</div>
);
}
}
解决方案
最好的放置位置this.setScrollLeft()
是componentDidUpdate
方法内部。
你已经this.setScrollLeft()
在里面调用了这个方法()componentDidMount
,这是对的。现在,您可以进行另一个调用componentDidUpdate
,它会像现在一样工作,因为componentDidUpdate
之前调用过render
。
The final outcome will be the same, however, you are separating the concerns: render
only render the components and the other methods deal with your business logic.
If you are not sure about componentDidMount
and componentDidUpdate
, see these excerpts from the official React.js documentation:
componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
推荐阅读
- reactjs - 自动建议/组合框建议不会显示
- sql-server - 计算 SQL 中每条记录发生事件以来的滚动时间
- vue.js - Vue.js。我无法将数据传输到对象
- javascript - Promise 中的返回值
- linux - 无论父文件夹名称如何,查找和排序唯一文件名
- javascript - 使用 Angular 库构建项目时出现问题。ng serve 在本地工作正常 错误消息是请添加 @NgModule 注释
- java - Webview 有时会显示空白页
- angular - mat-paginator 的最后一个或第一个按钮上是否有 EventListener?
- java - 使用服务帐号访问包含外部数据源的 BigQuery 表
- python - 使用标签 '{{value | 返回模型中的第一张图像 第一的}}'