在react js中的函数组件内部传递默认prop

时间:2020-07-16 12:10:18

标签: reactjs

我创建了一个带有2个道具的react组件:func1func2

const Component = ({ func1, func2 }) => {
  return (
          <Button
            onClick={() => {
              func1();
              func2();
            }}
            
          >
            Click
          </Button>
  );
};

上述组件是可重用的。在这种情况下,我将两个函数(func1,func2)都作为道具传递了:

<Component func1={functionA} func2={functionC}/>

我也有两种道具都不能通过的情况:

<Component func1={functionA}/>

在最后一种情况下,如何将func2设置为替代道具?

2 个答案:

答案 0 :(得分:1)

您可以在声明组件时简单地设置默认参数:

const Component = ({ func1, func2 = null }) => {
  return (
          <Button
            onClick={() => {
              func1();
              if (func2 && typeof func2 === "function") {
                func2();
              }
            }}
            
          >
            Click
          </Button>
  );
};

在没有提供道具的情况下,您的func2现在等于null(或您要分配的任何值)。

答案 1 :(得分:0)

下面是一个示例:

const ParentFunc2 = () => {
  console.log("ParentFun2");
};

export default function App() {
  return (
    <div className="App">
      <TestComponent func2={ParentFunc2} />
    </div>
  );
}

TestComponent:

import React from "react";

const func1Default = () => {
  console.log("func1");
};

const func2Default = () => {
  console.log("func2");
};

export default function TestComponent({
  func1 = func1Default,
  func2 = func2Default
}) {
  return (
    <button
      onClick={() => {
        func1();
        func2();
      }}
    >
      Click{" "}
    </button>
  );
}

实时示例:

https://codesandbox.io/s/falling-rgb-xidfe?file=/src/App.js