Reactjs 在React中有条件地添加函数作为prop?
我需要在React(Native)中有条件地添加一个函数 这段代码可以工作,但是当平台是web时,可能不需要调用Reactjs 在React中有条件地添加函数作为prop?,reactjs,Reactjs,我需要在React(Native)中有条件地添加一个函数 这段代码可以工作,但是当平台是web时,可能不需要调用onScroll事件,我认为这对性能不理想 <ScrollView onScroll={() => { if(Platform.OS === 'web') { return; } container.current?.onScroll(); }} > { 如果(Platform.OS==='
onScroll
事件,我认为这对性能不理想
<ScrollView
onScroll={() => {
if(Platform.OS === 'web') {
return;
}
container.current?.onScroll();
}}
>
{
如果(Platform.OS==='web'){
返回;
}
container.current?.onScroll();
}}
>
有没有办法有条件地设置
onScroll
prop?您可以使用&&
创建条件:
<ScrollView
onScroll={Platform.OS !== 'web' && () => container.current?.onScroll()}
>
container.current?.onScroll()}
>
您可以这样做,但就性能提升而言,这可能需要付出更多的努力。调用一个不做任何事情的函数的代价很小
您可以将道具构建为JSX之外的对象,并使用spread操作符将其传入,如下所示:
const scrollViewProps = {}
if (Platform.OS !== "web") {
scrollViewProps.onScroll = () => {
container.current?.onScroll()
}
}
<ScrollView {...scrollViewProps} />
constScrollViewProps={}
如果(Platform.OS!=“web”){
scrollViewProps.onScroll=()=>{
container.current?.onScroll()
}
}