在通过反应文档(https://reactjs.org/docs/integrating-with-other-libraries.html)进行探索时,我发现了以下代码段:
class Chosen extends React.Component {
componentDidMount() {
this.$el = $(this.el);
this.$el.chosen();
}
componentWillUnmount() {
this.$el.chosen('destroy');
}
render() {
return (
<div>
<select className="Chosen-select" ref={el => this.el = el}>
{this.props.children}
</select>
</div>
);
}
}
我不承诺的语法如下:
ref = {el => this.el = el}
该陈述是指什么?我觉得它与:
相同ref = { el => {
return this.el = el
}
}
但它是什么意思?这段代码中的流程是什么?
答案 0 :(得分:2)
el => this.el = el
是function(el) { this.el = el }
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)的分类。
ref
关键字用于获取元素参考以供将来使用,例如focus
事件。我们有两种方法可以使用ref
。
class MyComponent extends Component {
focusInput() {
this.refs.inputAge.focus();
}
render() {
return(
<input ref="inputAge" />
)
}
}
通过这种方式,所有参考都进入this.refs
。
class MyComponent extends Component {
focusInput() {
this.inputAge.focus();
}
render() {
return(
<input ref={ref => this.inputAge = ref} />
)
}
}
通过这种方式,我们可以在任何地方保留参考,因为我们通过功能控制它。