Enj*_*ayy 12 javascript reactjs
有没有办法让PropTypes从高阶组件内的组件指回到它们的创建位置?
这是一个很小的示例,但如果EnhancedButtons整个应用程序中存在多个单独的文件,那么调试将非常困难.
由于高阶组件理想地用于可重用性,我们可能永远不会知道缺少handleClick方法的组件的位置.render方法_EnhancedButton是Component我们想要增强的任何变量 .
是否有任何方法可以使PropTypes在创建它们的位置更加明显,例如FinalButton插入并且是一个实例_EnhancedButton并且缺少prop handleClick?
https://jsfiddle.net/kriscoulson/sh2b8vys/3/
var Button = (props) => (
<button onClick={ () => props.handleClick() }>
Submit
</button>
);
Button.propTypes = {
handleClick: React.PropTypes.func.isRequired
}
const EnhanceButton = Component => class _EnhancedButton extends React.Component {
render () {
return (<Component { ...this.props }>{this.props.children}</Component>);
}
}
const FinalButton = EnhanceButton(Button);
ReactDOM.render(
<FinalButton />,
document.getElementById('container')
);Run Code Online (Sandbox Code Playgroud)
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>Run Code Online (Sandbox Code Playgroud)
Lug*_*age 22
FinalButton您的示例中的名称将不会被反应,因为这只是您的本地变量名称,但我们将生成的组件的名称更改为您想要的任何名称.在这里,无论原始名称是什么,我都会使用"Final".
此外,我们可以将prop类型复制/合并到新元素.
function EnhanceButton(Component) {
class _EnhancedButton extends React.Component {
static displayName = 'Final' + (Component.displayName || Component.name || 'Component');
render() {
return (
<Component { ...this.props }>{this.props.children}</Component>
);
}
}
_EnhancedButton.propTypes = Component.propTypes;
return _EnhancedButton;
}
Run Code Online (Sandbox Code Playgroud)
这给出了:警告:propType失败:handleClick未指定必需的prop Button.检查渲染方法FinalButton.
小提琴:https://jsfiddle.net/luggage66/qawhfLqb/
虽然Luggage的答案非常有效,但另一种可能更清晰的替代方法是将你的proptypes声明为静态,并在组件的主体内声明它们.
const EnhanceButton = Component => class extends React.Component {
static propTypes = {
children: PropTypes.node,
}
static defaultProps = {
children: false,
}
render () {
return (
<Component
{ ...this.props }
>
{this.props.children}
</Component>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5685 次 |
| 最近记录: |