如何解决React Native绑定null在这样的结构中做了什么:someFunction.bindnull,someHook
AScreen
显示AComponent
,component
有一个按钮可以使索引从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
可以使意图更加清晰。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。