blog
blog copied to clipboard
React输入型组件的API设计
-
defaultValue和value的设计
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"}}
/>
}
}