简体   繁体   中英

DRY jsx render method

I wonder if it is a better way to DRY this code, have you guys any ideas? The props are the same, just the component change...

render() {
    const { input: { value, onChange }, callback, async, ...rest } = this.props;

    if (async) {
      return (
        <Select.Async
          onChange={(val) => {
            onChange(val);
            callback(val);
          }}
          value={value}
          {...rest}
        />
      );
    }

    return (
      <Select
        onChange={(val) => {
          onChange(val);
          callback(val);
        }}
        value={value}
        {...rest}
      />
    );
  }

With:

let createElement = function(Component) {
    return (
        <Component onChange={(val) => { 
            onChange(val);
            callback(val);
            }}
            value={value}
        {...rest}
      />
    );
};

you can do

let selectAsync = createElement(Select.Async);
let select = createElement(Select);

You can render them in the jsx part with {{select}} and {{selectAsync}}

PS: I didnt test this directly, but did something very similar a few days ago, so this approach should work. Note that Component must start with a capital letter.

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