我想做一个如果有 props有value传入,就使用 props的value,没有传入的话,就使用自有状态的 <MyInput /> 元件 代码如下
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} />
}
}
但我认为这样的代码有点冗长,似乎考虑不周,请问有没有这种元件的比较好的写法可以推荐呢?
首先,不要在
constructor()
方法中,使用this.props
,这个写法在IE下无法兼容。其次,
componentWillReceiveProps()
方法,将会废弃。可以做如下的修改:
你的需求是项目中最常见的使用方式: