网站搜索

reactjs - 在点击函数式组件时通过 onClick 设置 react 状态(TypeScript)


const NavBar = () => {
    const [active, setActive] = useState<string>("tasks");

    return {
        <Container>
            <MenuLink onClick=(() => setActive("settings")/>
            <MenuLink onClick=(() => setActive("tasks")/>
            <MenuLink onClick=(() => setActive("wallets")/>
        </Container>
    }

MenuLink.tsx:

interface MenuLinkProps {
  $active: boolean;
  to: string;
  title: string;
}

function MenuLink({ $active, to, title, ...rest }: MenuLinkProps) {
  return (
    <Container $active={$active} to={to} {...rest}>
      {title}
    </Container>
  );
}

interface ContainerProps {
  $active: boolean;
  to: string;
}

const Container = styled(Link)<ContainerProps>`
  width: 70px;
  height: 35px;

  display: flex;
  justify-content: center;
  align-items: center;

  border-radius: 3px;

  font-style: normal;
  font-weight: 500;
  font-size: 14px;
  line-height: 17px;
  letter-spacing: 0.025em;

  text-decoration: none;

  color: ${({ $active }: ContainerProps) => ($active ? "#4C6C94" : "#908E87")};
  background: ${({ $active }: ContainerProps) => ($active ? "#1D232B;" : "#100F0D")};

  &:not(:first-child) {
    margin-left: 24px;
  }
`;

我想在每次点击 MenuLink 项时触发 setActive。然而,TypeScript 抱怨我在 MenuLinkProps 中没有 onClick 作为属性。我不确定这是否正确,因为当我把 onClick 作为属性时,我会得到这个错误:

Cannot update a component (`NavBar`) while rendering a different component (`MenuLink`). To locate the bad setState() call inside `MenuLink`, follow the stack trace as described in

我不太确定应该如何在自定义组件中使用 onClick(以及其他标准“props”)。

答案#1

你可以更改你的导航栏界面为

interface MenuLinkProps {
  $active: boolean;
  to: string;
  title: string;
  [key : string] : any
}

接受静态的任何属性 这不会修复你的错误,请提供你在哪里以及如何使用 $active

答案#2

所以,你将必须将父组件的点击方法作为 props 传递给子组件

父组件:

const NavBar = () => {
  const [active, setActive] = useState<string>("tasks");


  var menuOnClick: (action:string) => {setActive(action)};


  return {
    <div>
      <Container>
          <MenuLink onClick=(this.menuOnClick} />
          <MenuLink onClick=(this.menuOnClick} />
          <MenuLink onClick=(this.menuOnClick} />
      </Container>
    </div>
  }
}

子组件:

<Container $active={$active} to={to} {...rest} onClick ={() => this.props.onClick(title)} >
{title}
</Container>