React Native绑定null在这样的结构中做了什么:someFunction.bindnull,someHook

问题描述

AScreen显示AComponentcomponent一个按钮可以使索引从0开始递增,当索引达到5时,AComponent将由BComponent代替。 BComponent一个按钮,可以带回AComponent并将索引重新设置为0。

backToACallBack.bind(null,useCurrentIndex)在以下代码中做什么?为什么绑定null

export default function AScreen() : JSX.Element {
  const backToACallBack = (useCurrentIndex) => {
    const [,setCurrentIndex] = useCurrentIndex;
    setCurrentIndex(0);
  };

  return (
    <AComponent
      panel={( useCurrentIndex ) => (
        <BComponent onBackToACallBack={backToACallBack.bind(null,useCurrentIndex)} />
      )}
    />
  );
}

export interface AComponentProps {
  panel: (
    useCurrentIndex: [number,React.dispatch<React.SetStateAction<number>>],) => JSX.Element;
}

export default function AComponent({ panel }: AComponentProps): JSX.Element {
  const [currentIndex,setCurrentIndex] = useState(0);
  return (
    <View>
      <View style={ currentIndex >=5 ? { display:none } : { flex:1 } }>
        <TouchableOpacity onPress={() => setCurrentIndex(currentIndex + 1)}>
          <Text>INCREMENT</Text>
        </TouchableOpacity>
      </View>
      <View style={ currentIndex >=5 ? { flex:1 } : { display:none } }>
        {panel([currentIndex,setCurrentIndex])}
      </View>
    </View>
  );
}

export interface BComponentProps {
  onBackToACallBack: () => void;
}

export default function BComponent({ onBackToACallBack }: BComponentProps): JSX.Element {
  return (
    <TouchableOpacity onPress={onBackToACallBack}>
      <Text>BACK TO A</Text>
    </TouchableOpacity>
  );
}

解决方法

.bind的第一个参数是在函数this上使用的.bind值-但箭头函数始终具有词法this,并且backToACallBack始终不引用this,因此传递给.bind的第一个值是什么都无关紧要。

.bind的第二个参数是调用该函数的第一个参数。例如,function foo(a){ ... } const bound = foo.bind(null,5);导致在调用bound时,使用foo的{​​{1}}参数调用a

类似地,这里的5产生了一个函数,该函数在被调用时以参数backToACallBack.bind(null,useCurrentIndex)调用backToACallBack

在没有useCurrentIndex的情况下执行相同操作的另一种方法是:

.bind

如果使用<BComponent onBackToACallBack={() => { backToACallBack(useCurrentIndex); }} /> ,但绑定的函数是箭头函数或未引用.bind,则第一个参数可以是 anything ,因为它没有使用(但是您需要传递第一个参数,然后才能传递第二个参数this)。像我上面那样使用匿名函数代替useCurrentIndex可以使意图更加清晰。