首先我们自定义一个Form组件,该组件用于包裹所有需要包裹的表单组件,通过contex向子组件暴露两个属性:
- model:当前Form管控的所有数据,由表单name和value组成,如{name:'ConardLi',pwd:'123'}。model可由外部传入,也可自行管控。
- changeModel:改变model中某个name的值。
- class Form extends Component {
- static childContextTypes = {
- model: PropTypes.object,
- changeModel: PropTypes.func
- }
- constructor(props, context) {
- super(props, context);
- this.state = {
- model: props.model || {}
- };
- }
- componentWillReceiveProps(nextProps) {
- if (nextProps.model) {
- this.setState({
- model: nextProps.model
- })
- }
- }
- changeModel = (name, value) => {
- this.setState({
- model: { ...this.state.model, [name]: value }
- })
- }
- getChildContext() {
- return {
- changeModel: this.changeModel,
- model: this.props.model || this.state.model
- };
- }
- onSubmit = () => {
- console.log(this.state.model);
- }
- render() {
- return <div>
- {this.props.children}
- <button onClick={this.onSubmit}>提交</button>
- </div>
- }
- }
(编辑:晋中站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|