已编辑:将React 的FancyButton示例添加到代码沙箱以及与React.forwardRef
React 16.3 中的新 api 一起使用的自定义道具检查功能。React.forwardRef
api 返回一个带有render
函数的对象。我正在使用以下自定义道具检查器来验证此道具类型。- 感谢 Ivan Samovar 注意到这一需求。
FancyButton: function (props, propName, componentName) {
if(!props[propName] || typeof(props[propName].render) != 'function') {
return new Error(`${propName}.render must be a function!`);
}
}
你会想要使用PropTypes.element
. 实际上......PropType.func
适用于无状态功能组件和类组件。
我已经制作了一个沙箱来证明它是有效的......考虑到我一开始给你错误的信息,我认为这是必要的。对此非常抱歉!
工作沙箱示例!
以下是链接失效时的测试代码:
import React from 'react';
import { render } from 'react-dom';
import PropTypes from "prop-types";
class ClassComponent extends React.Component {
render() {
return <p>I'm a class component</p>
}
}
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
const FSComponent = () => (
<p>I'm a functional stateless component</p>
);
const Test = ({ ClassComponent, FSComponent, FancyButton }) => (
<div>
<ClassComponent />
<FSComponent />
<FancyButton />
</div>
);
Test.propTypes = {
ClassComponent: PropTypes.func.isRequired,
FSComponent: PropTypes.func.isRequired,
FancyButton: function (props, propName, componentName) {
if(!props[propName] || typeof(props[propName].render) != 'function') {
return new Error(`${propName}.render must be a function!`);
}
},
}
render(<Test
ClassComponent={ ClassComponent }
FSComponent={ FSComponent }
FancyButton={ FancyButton } />, document.getElementById('root'));