reactjs React Native Button onPress函数和 prop 问题

fkaflof6  于 2022-12-29  发布在  React
关注(0)|答案(1)|浏览(157)

我有React原生项目。我是新的React。我被告知不要把函数在jsx中,因为这是不好的做法。寻找指导,以保持组件清洁

// App.js
export const App = () => {
  // other things
  return (
          <CustomButton onButtonPress={()=> someFunction} />
  )
}

然后我的自定义组件,我的问题。我应该创建一个函数,其中将包括 prop 或我使用 prop 直接在jsx

export const CustomButton = (props) => {
  <Button
    onPress={() => props.onButtonPress(item.socketId)}>
    Decline
   </Button>

export const CustomButton = (props) => {
  const handleDisconnect = (socketId) => {
    props.onButtonPress(socketId)
  }

  <Button
    onPress={() => handleDisconnect(item.socketId)}>
    Decline
   </Button>
fhity93d

fhity93d1#

长话短说。React使用函数组件,如果你不使用备忘录,你的函数将重新创建,并占用一些内存和时间。箭头函数也将重新创建。

import React, { memo, useCallback } from "react";
import { Text, Button } from "react-native";

const ClearCustomButtom = memo(({ onPress, title }) => (
  <Button onPress={onPress}>
    <Text>{title}</Text>
  </Button>
));

const ExtraCustomButtom = memo(({ onPress, title, socketId }) => {
  const handlePress = () => {
    console.log("Some extra action");
    onPress(socketId);
  };

  return (
    <Button onPress={handlePress}>
      <Text>{title}</Text>
    </Button>
  );
});

const RequestCustomButtom = memo(({ url, title }) => {
  const handlePress = () => {
    //send request on server
  };

  return (
    <Button onPress={handlePress}>
      <Text>{title}</Text>
    </Button>
  );
});

export default function App() {
  //UseCallback create point for put in button props, not function but point. Without useCallback component will rerender every time.
  const handlePressClearDecline = useCallback(() => {}, []);

  const handlePressExtraDecline = useCallback((socketId) => {
    console.log(socketId);
  }, []);

  return (
    <>
      <ClearCustomButtom
        title="ClearCustomButton"
        onPress={handlePressClearDecline}
      />
      <ExtraCustomButtom
        title="ExtraCustomButton"
        onPress={handlePressExtraDecline}
        socketId="777"
      />
      <RequestCustomButtom title="Send request" />
    </>
  );
}

这是react-native中最常见的例子,如何编写可按组件。

相关问题