在这里反应仍然相当新,但我想知道是否有办法检查组件是否正在使用某个道具与另一个?例如:
<Graph x={[1, 2, 3, 4]} points={10} />
让我们假设点prop为Graph组件分配一个随机的10个点,但使用该组件的人也可以传入一个带有数值数组的x
道具。
理论上,我想实现一个功能,当points
道具已被使用时,使用x
道具会在React中抛出错误或以某种方式警告用户。也许在这一点上有一个像console.log
一样简单的东西。
答案 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/