2017-01-04 71 views
0

我不知道是否更好的方法来干这个代码,你们有什么想法吗? 的道具是一样的,只是成分变化...DRY jsx渲染方法

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} 
     /> 
    ); 
    } 
+5

如果代码正在工作,并且您想要改进它,请将其发布到[codereview.se]。在你做之前,请看看[我如何提出一个好问题?](http://codereview.stackexchange.com/help/how-to-ask) – Tushar

+0

[React/JSX Dynamic Component Name] (http://stackoverflow.com/questions/29875869/react-jsx-dynamic-component-name) – Whymarrh

+0

@Tushar谢谢,我会记得下一次。 –

回答

1

有了:

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

你可以做

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

您可以用{{select}} and {{selectAsync}}的JSX部分使其

PS:我没有直接测试这个,但做了一些非常相似的事情几天前,所以这种方法应该工作。请注意,组件必须以大写字母开头。