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?