依赖注入
Web 组件的依赖注入
依赖注入的概念最早由
控制反转并非多么复杂的模式,我们可以将那些通过
# 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.