reactjs – React:如何通知父进行更改
发布时间:2020-12-15 20:12:54 所属栏目:百科 来源:网络整理
导读:我正在尝试将bootstrap包装到具有集成表单验证的组件中. 短: 让我说我有 Form FieldGroup Field rules={'required'}/ /FieldGroup/Form 一旦Field验证,我如何通知FieldGroup(父节点)添加类? 我创建了一个简化的codepen版本here 我想依赖验证状态,然后更改F
我正在尝试将bootstrap包装到具有集成表单验证的组件中.
短: <Form> <FieldGroup> <Field rules={'required'}/> </FieldGroup> </Form> 一旦Field验证,我如何通知FieldGroup(父节点)添加类? 我创建了一个简化的codepen版本here 我想依赖验证状态,然后更改FieldGroup的状态所以我可以正确更改类名. (添加has-warning has-danger等)并最终将类添加到Form组件. 解决方法
您需要将回调传递给子组件.我只是分叉你的codepen并添加了一些片段,如下所示.
http://codepen.io/andretw/pen/xRENee 这是主要概念, 即子组件需要额外的支持才能获得回调: <Form> <FieldGroup> <Field rules={'required'} cb={yourCallbackFunc}/> </FieldGroup> </Form> 在< FieldGroup />中(父): class FieldGroup extends React.Component{ constructor(props){ super(props); this.state = { color: 'blue' } } cb (msg) { console.log('doing things here',msg) } render() { const childrenWithProps = React.Children.map(this.props.children,child => React.cloneElement(child,{ cb: this.cb }) ) return ( <div class='fields-group'> <label> field </label> { childrenWithProps } </div> ); } }; 在< Field />中(儿童): class Field extends React.Component{ constructor(props){ super(props); this.state = { empty: true } this.validate = this.validate.bind(this); } validate(e){ let val = e.target.value; console.log(!val); this.setState({empty: !val}); //here to notify parent to add a color style! // do call back here or you may no need to return. this.props.cb(val) return !val; } render() { return ( <div> <input type='text' onBlur ={(event) => this.validate(event)}/> {this.state.empty && 'empty'} </div> ); } }; 你可以在回调函数中做你想做的事情. (您也可以将< Form />的回调传递给孙子并使其正常工作,但您需要重新考虑它的设计是好还是不好.) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |