我使用react-redux创建了一个简单的文本字段组件.
这是一个愚蠢的组件,因此它会收到一个回调函数来分派更改.
因此,在每次更改时,它都会更改其本地状态,而在Blur上,它会调用回调函数.
我认为我为这么简单的任务做了太多的事情,看起来有点矫枉过正,是否有更好/更短的方式来实现它?
export default class CreativeName extends Component {
constructor(props) {
super(props);
this.state = {
creativeName: props.creativeName
};
}
componentWillReceiveProps(nextProps) {
this.setState({
creativeName: nextProps.creativeName
});
}
onBlur() {
this.props.updateDraft('creativeName', this.state.creativeName);
}
onChange(e) {`enter code here`
this.setState({creativeName: e.target.value});
}
render() {
return (
<Row>
<Col lg={12} className="row-margin">
<ControlLabel>*Name</ControlLabel>
<div className="campaign-name">
<FormControl value={this.state.creativeName} type="text" onChange={(e) => this.onChange(e)}
onBlur={(e) => this.onBlur(e)} className="campaign-name-text-field" />
</div>
</Col>
</Row>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我真的建议使用redux-form.redux-form将输入值存储在全局状态.通过redux-from你可以有反应的组分的非常有用的输入标签.
例如:
import React, { Component, PropTypes} from 'react';
export default class FormInputTextBox extends Component {
static PropTypes = {
field: PropTypes.object.isRequired,
placeholder: PropTypes.string,
disabled: PropTypes.bool
}
render() {
const {field, placeholder, disabled} = this.props;
return (
<div>
<input
type="text"
{...field}
placeholder={placeholder}
disabled={disabled}
/>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6563 次 |
| 最近记录: |