检查一个propType是否与另一个内部Component一起使用

时间:2016-05-07 06:30:40

标签: reactjs properties components

在这里反应仍然相当新,但我想知道是否有办法检查组件是否正在使用某个道具与另一个?例如:

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

让我们假设点prop为Graph组件分配一个随机的10个点,但使用该组件的人也可以传入一个带有数值数组的x道具。

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

1 个答案:

答案 0 :(得分: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.
     }
  }
} 

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