【问题标题】:How to access nested props object in React TS?如何在 React TS 中访问嵌套的 props 对象?
【发布时间】:2021-09-01 04:53:37
【问题描述】:

我正在努力访问 React 中的嵌套 prop 对象

我有一个 Header 可重用组件,其中的道具是 className 和 title。

interface HeaderProps {
 className: string;
 title: ReactNode;
}

Header组件的用法如下。

<Header className='my-header' title={<Title color='red'> title of the page </Title>} /> 

现在在 Header 组件中,我想访问 Title 组件的颜色属性。

我正在考虑使用props.title.props.color。但是打字稿会抛出错误

props is not assignable to "whole ReactNode Thing"

【问题讨论】:

  • 试试这个 ---> `title: ReactElement;`
  • 哇...问题现在解决了。但我最近发现这样做是不好的做法。请在答案中添加此内容。我会接受的。

标签: javascript reactjs typescript react-props


【解决方案1】:

title: ReactNode 更改为title: ReactElement

import { ReactElement } from "react";
import "./styles.css";
// import * as React from 'react';

interface HeaderProps {
  className: string;
  title: ReactElement;
}

const Title = ({ color }: any) => {
  return <div>TITLE</div>;
};

const Header = ({ className, title }: HeaderProps) => {
  console.log(title.props.color);
  return <div>HEADER</div>;
};

export default function App() {
  return (
    <div className="App">
      <Header
        className="my-header"
        title={<Title color="red"> title of the page </Title>}
      />
    </div>
  );
}

codesandbox - https://codesandbox.io/s/holy-cherry-n6t50?file=/src/App.tsx:0-560

【讨论】:

    猜你喜欢
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 2018-10-29
    相关资源
    最近更新 更多