我正在尝试将 Bootstrap 包装到具有集成表单验证的组件中。
简短: 假设我有
<Form>
<FieldGroup>
<Field rules={'required'}/>
</FieldGroup>
</Form>
一旦Field
通过验证,如何通知FieldGroup
(父节点)添加类?
我创建了一个简化的codepen版本here
我想根据验证状态,然后更改 FieldGroup 的状态,以便我可以正确更改类名称。 (添加 has-warning
has-danger
等)并最终将类添加到 Form 组件。
最佳答案
您需要传递callback
到子组件。我刚刚 fork 了你的 codepen 并添加了一些代码片段,如下所示。
http://codepen.io/andretw/pen/xRENee
这是主要概念, 在 “父组件” 组件中创建回调函数,并将其传递给 “子组件” “组件
即子组件需要额外的 prop 来获取回调:
<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 />
( child ):
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 />
的回调传递给孙子并使其工作,但你需要重新考虑它的设计是否好。)
关于reactjs - react : how to notify parent for changes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40644092/