javascript - 如何在函数之间传递变量?
问题描述
朋友们,下午好。我有两个问题。
- 如何将 Fulloffset 传递给 scrollToRef 函数?
- 如何在对象中声明道具,以便它们在所有函数中都可用?我试图避免在每个函数中声明类似“const { arrayOfHeight } = this.props”
export function withScrollToFirstError(Component: t.form.Component): React.ComponentType {
class ScrollToFirstErrorHOC extends PureComponent<OuterProps & PropsFromState, ComponentState> {
constructor(props: OuterProps & PropsFromState) {
super(props);
this.state = {
height: 0,
offset: 0,
};
}
componentDidUpdate() {
this.existError();
}
existError = () => {
const { currentFieldId, firstFieldId, arrayOfHeight, fieldOffset, fieldErrors } = this.props;
this.calculateCoordinate();
};
calculateCoordinate = () => {
const fullOffset = offset + fieldOffset[0];
this.scrollToRef();
};
scrollToRef = () => {
if (this.props.reference) {
this.props.reference.current.scrollTo({
x: 0,
y: 0,
animated: true,
});
}
};
解决方案
将 Fulloffset 传递给 scrollToRef
calculateCoordinate = () => {
const fullOffset = offset + fieldOffset[0];
this.scrollToRef(fullOffset); // like this
};
scrollToRef = (fullOffset) => {
if (this.props.reference) {
this.props.reference.current.scrollTo({
x: 0,
y: 0,
animated: true,
});
}
};
全局声明 props
export function withScrollToFirstError(Component: t.form.Component): React.ComponentType {
class ScrollToFirstErrorHOC extends PureComponent<OuterProps & PropsFromState, ComponentState> {
constructor(props: OuterProps & PropsFromState) {
super(props);
this.state = {
height: 0,
offset: 0,
};
// initialize here
this.arrayOfHeight = props.arrayOfHeight;
}
componentDidUpdate() {
this.existError();
}
existError = () => {
// use here like
this.arrayOfHeight;
};
}
推荐阅读
- c++ - 为什么模板化的类数据成员需要 static 关键字?
- reactjs - 反应图像上传问题
- c# - 硒与 C#
- xpath - 标签之间的 Xpath 文本
- javascript - oneHot 中的错误:深度必须 >=2,但它是 1
- flutter - 小部件树中的提供者 - MaterialApp 和 Scaffold 之间的范围?
- javascript - 使用自定义 React 钩子提交带有数据的表单
- php - 如何在刀片 Laravel 中添加两个数字
- mysql - MySQL Workbench 不会连接到 AWS RDS DB。错误 - “无法连接到本地主机”
- spring-boot - WebClient 5.3+ 交换与 exchangeToMono。一起提取 cookie 和 body