简体   繁体   中英

React High Order Components

Lets says I have an array of objects where each object have structure like below

obj = {
    name:"Name1",
    description:"Description1",
    activeState:1,
    rating:5
}

const User = (obj) => {
    let userActiveState = (obj.activeState === 1) ? 'Active' : 'Non Active';

    return (
        <tr>
            <td>{obj.name}</td>
            <td>{obj.description}</td>
            <td>{userActiveState}</td>
        </tr>
    );
}

User.propTypes = {
    name: PropTypes.string
    description: PropTypes.string
    activeState: PropTypes.number
}

User.defaultProps = {
    name: "Not Available"
    description:""
    activeState: 0
}

I use this array to create UI using User(a stateless functional react component), but before the stateless functional react component spits out the UI I want to make some modification to the object properties which are required by the
UI (example using text instead of number for activeState) and not all the object properties are required too. Where would I remove unwanted properties so that I can have defaultProps and proptypes defined only for the required properties and would I use a high order component which transforms and filters the obj properties?

You don't need a HoC here - a simple composition is enough:

const Component = ...;

const ComponentButDifferentFormats = ({propToSkip, propToRename, ...props}) => (
  <Component
    {...props}
    propRenamed={propToRename}
    propX={parseFloat(props.propX)}
    propY={'' + props.propY}
  />
);

With this approach, you'll decouple the transformation logic from the real UI. It's really useful for example with an API response. Creating a HoC is also an option: it might be parametrized with formats, filters or even the component itself. One more function in the above example: Component => ... .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM