【问题标题】:React prop-type validation with currying functions使用 currying 函数反应 prop-type 验证
【发布时间】:2017-12-06 16:33:39
【问题描述】:

我对 React 比较陌生,遇到了一个问题,我无法验证从 curried 函数返回的组件上的 props。

我已经尝试在“列表”和“包装组件”上验证道具类型,但我仍然没有任何成功。在这个特定实例中,我将如何验证“数据”道具?

import React from "react";
import PropTypes from "prop-types";

const styles = {
  listStyles: {
    display: "flex",
    flexDirection: "row",
    flexWrap: "wrap",
    listStyle: "none",
  },
};

const List = WrappedComponent => ({ data }) => (
  <ul style={styles.listStyles}>
    {data &&
      data.map(item => (
        <div>
          <WrappedComponent {...item} />
        </div>
      ))}
  </ul>
);

List.propTypes = {
  data: PropTypes.array.isRequired,
};

export default List;

【问题讨论】:

    标签: javascript reactjs react-proptypes


    【解决方案1】:

    您将 propTypes 添加到外部函数而不是组件本身。

    const makeList = WrappedComponent => {
      const List = ({ data }) => (
        <ul style={styles.listStyles}>
          {data &&
            data.map(item => (
              <div>
                <WrappedComponent {...item} />
              </div>
            ))}
        </ul>
      );
    
      List.propTypes = {
        data: PropTypes.array.isRequired,
      };
    
      return List
    }
    

    【讨论】:

    • 这是有道理的。在这种情况下,我有办法验证数据的 propTypes 吗?
    • 什么意思?
    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    相关资源
    最近更新 更多