将状态作为道具传递



我想在一些子组件中显示一个按钮,而不在其他组件中显示。我在父组件中使用了useState,但无法将其传递给子组件。我该怎么做?

const [showRepo, setShowRepo] = useState(false);
const handleShowRepo = () => {
setShowRepo = !showRepo;

};

我在哪里使用它;

<button className={!showRepo ? `${styles.viewRepo} ${styles.hideRepo}` : `${styles.viewRepo}`}>
<a target="_blank" href={`${props.link}`}>
{props.buttonText}
</a>
</button> 

下面是一个如何将父组件状态传递给子组件使用的示例:

import React, { useCallback, useEffect, useState } from "react";
export function Parent() {
const [name, setName] = useState("Dolan The Duck");
return (
<div>
<h1>Dolan Family</h1>
<Child name={name} />
</div>
);
}
function Child(props) {
return <h2>I am Luffy! {props.name}'s son!</h2>;
}

让我们分解一下这个例子:

  1. Parent组件具有name状态,当它渲染Child时,它将状态变量作为名为name的道具传递

  2. Child组件使用道具name来渲染一个很酷的标题,它使用props.name.

点击此处了解更多

最新更新