Is it a good practice to call setState or other methods on this.props.children in React?

StackOverflow https://stackoverflow.com/questions/22501428

  •  17-06-2023
  •  | 
  •  

Pergunta

In my understanding, props are meant to be set by parent, and state is meant to be private to component.

this.state is private to the component and can be changed by calling this.setState(). When the state is updated, the component re-renders itself.

Parent component should not call setState on its children, ever. Is this correct?

Imagine parent <Form> has some validation mechanism on submitting, and wants to pass all <FormInput>s validation errors. Should it do this via props, or can it call setState on its children?

Finally, is it a good practice to call anything on child components?

Consider this method:

validate: function () {
  var hasError = false;

  React.Children.forEach(this.props.children, function(child) {
    if (child.validate) {
      hasError = hasError || child.validate();
    }
  });

  return !hasError;
}

It works, but I'm not sure duck-typing children methods is the way to go in React.
What do you think?

Foi útil?

Solução

It's not really a good idea.

With validation example, although it would work if your form had a few direct children components, what if you want to validate fields inside a <div> as well? They won't be immediate children, so now your logic constrains your markup.

One way to accomplish what you want is to give children exactly the level of control over parent's state they need by giving a special object. React has a built-in example of this: ReactLink and LinkedStateMixin.

You can take the same idea and apply it to validation.

Outras dicas

Every component in react is independent and each component should maintain their own state not the others. They can only send props to other components and its the other component decision to update its state or not. so its a better practice to send props to the children instead of calling setState of them.

However according to your question in case of form validation if a form is submitted and the form is invalid the the form triggers Invalid event on each of its input field.

So you can write functions to handle the invalid event on every child due to which you also don't have to pass props from parent to child.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top