Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

javascript - PropTypes on Higher Order Components

Is there a way for PropTypes from a component inside of a Higher Order Component to point back to where they were created?

enter image description here

This is a small sample but if there was multiple EnhancedButtons throughout an application in separate files this would be very hard to debug.

Since the Higher Order Component is ideally made for reusability we may never know the location of the component that is missing the handleClick method. The render method of _EnhancedButton is a variable for any Component that we want enhanced.

Is there any way to make the PropTypes more obvious where they are being created such as FinalButton which is inserted and is an instance of _EnhancedButton and is missing the 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')
);
<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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The name FinalButton in your example won't be known to react since that is just your local variable name, but we change the name of the resulting component to whatever you want. Here I use "Final" in front of whatever the original name was.

Also, we can copy / merge the prop types over to the new element.

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;
}

This gives: Warning: Failed propType: Required prop handleClick was not specified in Button. Check the render method of FinalButton.

Fiddle: https://jsfiddle.net/luggage66/qawhfLqb/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...