【问题标题】:how do I pass variables between functions?如何在函数之间传递变量?
【发布时间】:2020-11-12 10:46:34
【问题描述】:

朋友们,下午好。我有两个问题。

  1. 如何将 Fulloffset 传递给 scrollToRef 函数?
  2. 如何在对象中声明道具,以便它们在所有函数中都可用?我试图避免在每个函数中声明类似“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,
        });
      }
    };

【问题讨论】:

    标签: javascript function react-native scope


    【解决方案1】:

    将 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;
        };
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-04
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      • 2013-03-07
      • 1970-01-01
      相关资源
      最近更新 更多