blog icon indicating copy to clipboard operation
blog copied to clipboard

React输入型组件的API设计

Open jun-lu opened this issue 6 years ago • 0 comments

  • defaultValuevalue 的设计
class CustomInput extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      value: this.props.defaultValue
    };
  }

  onChange = (e)=>{
    this.setState({
      value: e.value
    })
  }
  
  getCurValue(){
    return 'value' in this.props ? this.props.value : this.state.value;
  }

  render() {
    const value = this.getCurValue();
    return <input value={value} onChange={this.onChange} />
  }
}

ReactDOM.render(
    <CustomInput defaultValue={"1231"} />,
    mountNode
);

  • 需要二次确认的输入型组件

class CustomInput extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      value: this.props.value
    };
  }
	
  componentWillReceiveProps(nextProps){
    if(nextProps.visible && nextProps.visible !== this.props.visible){
      this.setState({
        value: nextProps.value
      })
    }
  }
  
  onChange = (e)=>{
    this.setState({
      value: e.value
    })
  }
  

  render() {
    const value = this.state.value;
    return <input 
    	value={value} 
    	onChange={this.onChange} 
    	style={{display: this.props.visible ? "block" : "none"}}
		/>
  }
}

jun-lu avatar Mar 19 '19 12:03 jun-lu