blog icon indicating copy to clipboard operation
blog copied to clipboard

React组件 value 与 defaultValue

Open jun-lu opened this issue 7 years ago • 1 comments

value 和 defaultValue 应该成对设计出现吗?

jun-lu avatar Nov 08 '18 07:11 jun-lu

应该,defaultValue 解决了使用者对组件的 惰性控制 需求。 value解决了,强控制需求。并且在组件不需要控制的时候2个都不传。

不需要 componentWillReceiveProps 生命周期参与的代码设计



class ABC extends React.Component{
  static propsTypes = {
    defaultValue: PropTypes.string,
    value: PropTypes.string
  }

  static defaultProps = {
    defaultValue: undefined,
    value: undefined
  }
  
  constructor(props){
    super(props);
    //初始化把 defaultValue 赋值到 state中
    this.state = {
      value: this.props.defaultValue
    }
  }

  onChangeValue(newValue){
    //如果是强控制,那么想必一定监听了onChange
    if(this.props.onChange){
      this.props.onChange(newValue)
    }

    //把新的值设置到 state中
    this.setState({
      value: newValue
    })
  }

  isPropsValue(){
    return this.props.value !== undefined;
  }

  getValue(){
    //如果有 props.value 不是 undefined ,那么久使用 props.value 否则使用 state.value
    return this.isPropsValue() ? this.props.value : this.state.value;
  }

  render(){
    
    const value = this.getValue();
    return ...
  }
}

jun-lu avatar Nov 14 '18 08:11 jun-lu