您收到“未定义”响应的原因是因为正如 @Zrogua 所提到的,onClick 是一个事件侦听器函数,而不是一个持久值(如您定义的状态)。
import React from "react";
const YourButton = ({ onClick }) => {
console.log(onClick);
return <section>{onClick && <button>here</button>}</section>;
};
const ParentDiv = () => {
return (
<div>
<h1>Button Props</h1>
<h2>Start editing to see some magic happen!</h2>
<YourButton onClick={() => console.log("CLICK")} />
</div>
);
};
export default ParentDiv;
console.log() 的结果:
function onClick() // index.js:27:25
之所以这样是因为props是read-only。来自 React 文档:
无论您将组件声明为函数还是类,它都不能修改自己的 props ... 这样的函数被称为“纯”,因为它们不会尝试更改输入,并且总是返回相同的结果相同的输入。
因此,您的按钮只有在定义了onClick 函数时才会显示。比如你没有给onClick一个函数或者值,按钮就不会出现:
import React, { useState } from "react";
const YourButton = ({ onClick }) => {
console.log(onClick);
return (
<section>
{onClick && <button>This button is shown if a button is defined.</button>}
</section>
);
};
const ParentDiv = () => {
return (
<div>
<h1>Button Props</h1>
<YourButton onClick={() => console.log("CLICK")} />
<YourButton /> {/* You won't see this button because the function is not defined. */}
</div>
);
};
export default ParentDiv;
出现按钮是因为 prop 的值不是未定义的(您的 onClick 函数),并且因为它是只读的,所以您无法在子组件中访问该函数。
相反,(1) 在父组件中定义模态状态,(2) 通过 props 将状态传递给按钮,如下所示:
import React, { useState } from "react";
const YourButton = ({ onClick }) => {
console.log(onClick);
return (
<section>
{onClick && <button>This button is shown if a button is defined.</button>}
</section>
);
};
const AltButton = ({ modal }) => {
return (
<section>
{modal && (
<button>This button is shown the modal state is passed.</button>
)}
</section>
);
};
const ParentDiv = () => {
const [modal, setModal] = useState(false);
return (
<div>
<h1>Button Props</h1>
<YourButton onClick={() => console.log("CLICK")} />
<YourButton />{" "}
{/* You won't see this button because the function is not defined. */}
<section>
<button onClick={() => setModal(!modal)}>OPEN MODAL</button>
</section>
{modal && <p>this is dependent on state</p>}
<AltButton modal={modal} />
</div>
);
};
export default ParentDiv;
工作代码沙盒:https://codesandbox.io/s/stack-66715327-passingfunctions-92pzr
最后,如果我在字里行间阅读并正确理解您希望在打开模式时隐藏按钮,这里是我用于打开模式的按钮的一个小的模式包装技巧:https://codesandbox.io/s/stack-66715327-modalwrapper-wvl54