我正在尝试将bootstrap包装到具有集成表单验证的组件中. 短: 让我说我有 Form FieldGroup Field rules={'required'}/ /FieldGroup/Form 一旦Field验证,我如何通知FieldGroup(父节点)添加类? 我创建了一个简
短:
让我说我有
<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 />的回调传递给孙子并使其正常工作,但您需要重新考虑它的设计是好还是不好.)
