应如何将初始状态计算(例如:验证)传递回React中的父级



假设我们有一个带有父组件和子组件的设置。我希望遵循"dumb"组件模式,即数据从上到下流动,然后使用onChange回调通知父级。

不过,我有点困惑,如何将其应用于内部可能有Form的组件。假设Parent需要知道组件中的数据是否有效,但验证逻辑是否在Form组件中。有没有一种好的方法可以在不通过ref调用表单组件的情况下仍然遵循这种模式?

在典型的MVC中,验证/计算将在传递的模型上进行。

class Parent extends React.Component {
   constructor () {
      this.state = {
        value: {},
        isValid: this.isValid()
      };
   }
   render () {
      return (
        <Form props={this.props.fields} onChange={this.onChange}></Form>
      );
   }
  
   isValid () {
      //what should I do here? 
   }
  
   onChange (change) {
     this.setState({
        values: change.values,
        isValid: change.isValid
      });
   }
}
class Form extends React.Component {
   render () {
      //return some form stuff 
   }
  
   onChange (value) {
      //fancy internal validation logic
 
     this.props.onChange({
        values: value,
        isValid: resultFromValidationLogic
      });
   }
}

如果Parent需要知道验证的结果,那么我会将验证放在Parent中。

在React自上而下的范式中,将某些内容存储/执行在较低阶组件中是没有意义的,而较高阶组件需要了解这些内容。输入值除外;它们是变更处理程序中唯一应该包含的内容。

此外,这种方式isValid不需要处于该状态。它可以从状态派生。我会调用Parent渲染函数中的验证。

这是我适度的改写:

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      values: {}
    };
  }
  isValid(values) {
    // perform validation here
  }
  handleChange(values) {
    this.setState({
      values: values
    });
  }
  render() {
    const isValid = this.isValid(this.state.values);
    return (
      <Form
        props={this.props.fields}
        values={this.state.values}
        onChange={(values) => this.handleChange(values)}
        isValid={isValid}
      />
    );
  }
}
class Form extends React.Component {
  handleChange(values) {
    this.props.onChange(values);
  }
  render() {
     // return some form stuff
  }
}

最新更新