2017-06-29 97 views
5

我最近开始使用反应,我倾向于这样定义的默认值:的defaultProps VS逻辑或

class TextInput extends Component { 
    render() { 
     return (
      <input 
       type="text" 
       name={ this.props.inputName || 'inputName' } 
       style={ this.props.inputStyle || {} } 
       className={ this.props.inputClass || '' } 
      /> 
     ); 
    } 
} 

代替:

class TextInput extends Component { 
    render() { 
     return (
      <input 
       type="text" 
       name={ this.props.inputName} 
       style={ this.props.inputStyle} 
       className={ this.props.inputClass} 
      /> 
     ); 
    } 
} 

TextInput.defaultProps = { 
    inputName: 'inputName', 
    inputStyle: {}, 
    inputClass: '' 
} 

没有这种方法有对比有什么缺点使用defaultProps

回答

6

这种方法与使用defaultProps相比有什么缺点?

在您特定的代码示例中;没有,因为你只使用每个道具一次。但是,想象一下在很多地方使用特定道具的大型应用程序,如果该值是虚假的,手动定义“后退值”将变得非常繁琐。

另外想象一下,如果你突然决定改变这个值到不同的东西;那么您将不得不遍历整个组件,并在使用该特定道具的地方进行更新。这会使其容易出错和错误。

你的方法的另一个问题是,如果你真的需要一个特定的道具是falsy,如null0。那么你的情况就会失败,而使用“后备价值”来代替。


所以基本上,使用defaultProps使得管理你的道具更容易一点,更全面的和可管理的。

顺便说一句,为了供您参考,您使用的逻辑表达式称为Short-circuit evaluation

+0

我明白了,谢谢你的回答 – sleepwalker00

2

这两种方法的工作都是正确的。如果你必须在多个地方使用道具会怎么样?您将最终在代码中的任何地方编写逻辑操作。默认的道具可以定义一次,没有任何问题。

但是,您可以使用任一种方式。它只是一个编码风格的问题。