如何在子组件的情况下渲染父组件? 如果任何一个孩子无效,我想在父母中禁用按钮。 但是验证位于子组件内部。
class Parent extends React.Component {
constructor(props){
super(props);
this.state = {data: [
{type: "text", value: ""},
{type: "email", value: "not valid email"}
]};
isAnyChildInvalid(){
// How can I get information about my childs
}
render(){
<div>
this.state.data.map((item, index) => <Child key={index} data={item} />
<button disabled={isAnyChildInvalid()} label="send">
</div>
}
}
class Child extends React.Component {
isValid(){
let valid = true;
switch(this.props.data.type){
case "text":
break;
case "email":
valid = (/\w+@\w+\.\w+/).test(this.props.data.value);
break;
default:
valid = true;
}
tellParentThatIAmValidOrNot(valid);
return valid;
}
tellParentThatIAmValidOrNot(valid){
// How to tell Parent that i am valid or not?
// The validation is used before any changes to input is done
}
render(){
<input type={this.props.data.type} value={this.props.data.value} className={this.isValid() ? "valid" : "invalid" }/>
}
我不希望将所有验证都移至“父组件”,因为再次在另一个“父组件”中使用了“孩子”。
答案 0 :(得分:1)
React中的数据仅沿一个方向流动,因此无法将数据从子级传递到父级。但是您可以将函数从Parent传递给Child,该函数需要一些参数,然后可以在Child Component内部的函数调用中传递。
我会做这样的事情。 首先,在父组件中,我将创建一个具有“无效”参数的函数,该参数将为布尔值。
class Parent extends React.Component {
constructor(props){
super(props);
this.state = {data: [
{type: "text", value: ""},
{type: "email", value: "not valid email"}
]};
isAnyChildInvalid(invalid){
if (invalid) {
doSomething();
}
}
...
}
然后我将通过道具将该函数传递给子组件。
render(){
<div>
this.state.data.map((item, index) => <Child validateChild={this.isAnyChildInvalid} key={index} data={item} />
<button disabled={isAnyChildInvalid()} label="send">
</div>
}
然后在Child组件中,我将调用tellParentThatIAmValidOrNot函数中从Parent传递的函数。
tellParentThatIAmValidOrNot(valid){
this.props.validateChild(valid);
}