【问题标题】:TypeScript React: How to pass all props to child functionTypeScript React:如何将所有道具传递给子函数
【发布时间】:2019-11-08 10:55:20
【问题描述】:

我是 Typescript React 的新手。在将以下 React JS 代码转换为 Typescript React 时需要帮助。我真的很困惑如何将道具传递给子函数。

反应 JS

blog.js

    import contentarea from './contentarea.js';
    export default function Blog() {
    return (
    <contentarea wid={12} hei={6}>
    </contentarea>
    );
    }

contentarea.js

   import PropTypes from "prop-types";
   export default function contentarea(props) {
   const { children, ...rest } = props;
   return (
   <contentarea  {...rest}>
   {children}
   </contentarea>
   );
   }    

   contentarea.propTypes = {
   children: PropTypes.node
   };

提前致谢!

【问题讨论】:

  • 使用 React 的上下文。通过这个网址了解更多信息:reactjs.org/docs/context.html
  • 谢谢Bhawana..会通过它...
  • React 组件名称必须大写

标签: reactjs typescript


【解决方案1】:

这不是特定于打字稿的,如果我对您的问题的理解是正确的,您希望将 wid 和 hei 传递给“孩子”中的组件,以便您可以将其包装在 HOC 下

const PropWrapper = (WrappedComponent, givenProps) => {
const hocComponent = ({ ...props }) => <WrappedComponent {...props} {...givenProps} />

hocComponent.propTypes = {
}

return hocComponent}

在渲染子元素之前使用 to

<contentarea>{PropWrapper(children, rest)}</contentarea>

希望对你有帮助

【讨论】:

  • 感谢@Nightraiser!这个答案非常接近查询。将在这里试用并更新。
  • 当然@NightRaiser,但我不得不暂停这项工作一段时间。一旦我恢复它并尝试解决方案,就会将答案标记为已接受。谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-06-01
  • 2020-08-08
  • 2020-07-17
  • 2023-01-13
  • 2020-03-12
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
相关资源
最近更新 更多