依赖注入

Web 组件的依赖注入

依赖注入的概念最早由 Google Angular 引入到 Web 前端编码中,而随着组件化概念的流行,特别是类组件的方式逐步成为主流,我们也可以在前端编码中实践依赖注入或者控制反转的模式。

控制反转并非多么复杂的模式,我们可以将那些通过 Props 传入的 Every function passed in via props is an “injection of a dependency”, and every component that declares a prop for handling events or user interaction is observing “inversion of control”. The borrowed terms have now been rendered obsolete through ubiquity, save perhaps for use as shibboleth for JavaScripters who have lived through the reign of Angular.

# Constructor Injection

As the name implies, this component would receive its dependencies via the constructor. Here’s what such a component would look like:

class Knight extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      weapon: props.weapon
    };
  }
  render() {
    return `🐴 ${this.state.weapon}`;
  }
}

And you would use it like this:

<Knight weapon={sword} />

Of course, you should typically use the prop directly instead of duplicating it.

Setter Injection

Instead of setting dependencies in the constructor, a component would have methods available that can be called after initialization, with dependencies passed in as the argument.

class Knight extends React.Component {
  state = {};
  setWeapon = weapon => this.setState({ weapon });
  render() {
    return `🐴 ${this.state.weapon}`;
  }
}

Usage:

componentDidMount () {
  this.knight.setWeapon(sword);
}
render () {
  return <Knight ref={c => this.knight = c} />;
}

Again, you almost certainly would not want do this instead of passing dependencies directly via props.

Interface Injection

The props of a component are its interface to its clients, thus “required props” would come the closest to an analogy for interface injection with React:

class Knight extends React.Component {
  static propTypes = {
    weapon: PropTypes.any.isRequired
  };
  render() {
    return `🐴 ${this.props.weapon}`;
  }
}

and you would use it simply as

<Knight weapon={sword} />

I hope these examples illustrate how commonplace Dependency Injection has become, and gave you some talking points should the topic ever comes up.

下一页