React PropTypes:允许一个prop的不同类型的PropTypes

时间:2017-01-23 14:16:48

标签: reactjs react-proptypes

我有一个组件可以接收其大小的道具。道具可以是字符串或数字:"LARGE"17

我可以让React.PropTypes知道这可以是propTypes验证中的一个吗?

如果我没有指定类型,我会收到警告:prop type `size` is invalid; it must be a function, usually from React.PropTypes.

MyComponent.propTypes = {
    size: React.PropTypes
}

5 个答案:

答案 0 :(得分:417)

MySqlCommand command = new MySqlCommand(selectCmd, myConnection);
                    command.CommandText = "SELECT idtolistsubsoorten FROM `vogelsoort` WHERE id= MAX (id)and vogelsoort.naam =@vogelsoortnam";
                    command.Parameters.Add("@vogelsoortnaam", MySqlDbType.VarChar).Value = vogel.Soortnaam;
                    reader = command.ExecuteReader();
                    reader.Read();
                    while (reader.Read())
                    {
                        string idpape = reader.;
                        subid = Convert.ToInt64(idpape);
                    }

了解详情:Typechecking With PropTypes

答案 1 :(得分:9)

出于文档目的,最好列出合法的字符串值:

size: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.oneOf([ 'SMALL', 'LARGE' ]),
]),

答案 2 :(得分:6)

这可能对您有用:

height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

答案 3 :(得分:0)

这是使用多个原型和单个原型的示例。

import React, { Component } from 'react';
import { string, shape, array, oneOfType } from 'prop-types';

class MyComponent extends Component {
  /**
   * Render
   */
  render() {
    const { title, data } = this.props;

    return (
      <>
        {title}
        <br />
        {data}
      </>
    );
  }
}

/**
 * Define component props
 */
MyComponent.propTypes = {
  data: oneOfType([array, string, shape({})]),
  title: string,
};

export default MyComponent;

答案 4 :(得分:-1)

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    let cell = tableView.cellForRow(at: indexPath)
    if cell?.isSelected == true { // check if cell has been previously selected
        tableView.deselectRow(at: indexPath, animated: true)
        return nil
    } else {
        return indexPath
    }
}