我创建了一个带有2个道具的react组件:func1
,func2
。
const Component = ({ func1, func2 }) => {
return (
<Button
onClick={() => {
func1();
func2();
}}
>
Click
</Button>
);
};
上述组件是可重用的。在这种情况下,我将两个函数(func1,func2)都作为道具传递了:
<Component func1={functionA} func2={functionC}/>
我也有两种道具都不能通过的情况:
<Component func1={functionA}/>
在最后一种情况下,如何将func2
设置为替代道具?
答案 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>
);
}
实时示例: