【问题标题】:Check if one propType is used with another inside Component检查一个 propType 是否与另一个内部组件一起使用
【发布时间】:2016-05-07 06:30:39
【问题描述】:

这里的 React 还是比较新的,但我想知道是否有办法检查 组件是否将某个 prop 与另一个组件一起使用?例如:

<Graph x={[1, 2, 3, 4]} points={10} />

假设 points 属性为 Graph 组件分配了一个随机的 10 个点,但使用该组件的人也可以传入带有数值数组的 x 属性。

理论上,我想实现一个功能,当 x 道具已经在使用时,使用 points 道具会在 React 中引发错误或以某种方式警告用户。也许在这一点上,像console.log 这样简单的东西。

【问题讨论】:

    标签: reactjs properties components


    【解决方案1】:

    您可以使用 propTypes 进行检查

    propTypes: {
      points: function(props, propName, componentName) {
         if(props.x != undefined){
            console.log("You cannot use points and x at the same time");
            return new Error("You cannot use points and x at the same time"); // Use this if you want to throw an error.
         }
      }
    } 
    

    这是一个例子 -> https://jsfiddle.net/69z2wepo/41180/

    【讨论】:

      猜你喜欢
      • 2016-10-05
      • 2015-10-11
      • 2020-04-30
      • 2016-08-16
      • 1970-01-01
      • 2012-10-08
      • 2022-11-13
      • 2013-02-22
      • 2015-09-09
      相关资源
      最近更新 更多