React can optionally use its own state or props components

I want to make a < MyInput / > element code with its own state if there is a props with value passed in, and if the value, using props is not passed in, the code is as follows

DEMO: https://stackblitz.com/edit/r.

import React from "react";

export default class MyInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: (typeof this.props.value === "string") ? this.props.value : ""
    }
  }
  componentWillReceiveProps(nextProps) {
    if ((typeof this.props.value === "string") ? this.props.value : "") {
      this.setState({ value: nextProps.value })
    }
  }

  handleChange = (e) => {
    if (this.props.onChange) {
      this.props.onChange(e);
    } else {
      this.setState({ value: e.target.value });
    }

  }
  handleClick = (e) => {
    if (this.props.onClick) {
      this.props.onClick(e);
    } else {

    }
  }

  render() {
    return <input value={this.state.value} onClick={this.handleClick} onChange={this.handleChange} />
  }
}

but I think this kind of code is a bit lengthy and seems to be ill-considered. Is there a better way to write this component that can be recommended?

May.31,2021

first of all, do not use this.props in the constructor () method, which is not compatible with IE.

secondly, the componentWillReceiveProps () method will be discarded.

you can make the following changes:

import React from 'react';

export default class MyInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    }
  }


  handleChange = (e) => {
    if (this.props.onChange) {
      this.props.onChange(e);
    } else {
      this.setState({ value: e.target.value });
    }

  }
  handleClick = (e) => {
    if (this.props.onClick) {
      this.props.onClick(e);
    } else {

    }
  }

  render() {
    return <input value={(typeof this.props.value === 'string') ? this.props.value :this.state.value} onClick={this.handleClick} onChange={this.handleChange} />
  }
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1bdbd0e-31294.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1bdbd0e-31294.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?