从反应快速入门:https://facebook.github.io/react/docs/lifting-state-up.html https://facebook.github.io/react/docs/lifting-state-up.html
该线的目的:
handleChange(e) {
this.props.onChange(e.target.value);
}
从未被解释过,我不明白它是什么does。 onChange 是 props 的内置方法吗?我以为 props 只是组件的参数,为什么它可以调用函数呢?
我带着同样的问题来到这里,但我现在明白了(至少我认为我明白了)。问题是onChange
in the Calculator
类是一个道具,但在类的渲染部分TemperatureInput
,它是一个事件监听器。有时我在 React 中看到这种情况,其中相同的名称用于两个完全不同的事物,我发现它很容易造成混乱。以下代码块中发生的情况如下:
class TemperatureInput extends React.Component {
handleChange(e) {
this.props.onChange(e.target.value); **(2)**
}
render() {
return (
<fieldset>
<input value={value} onChange={this.handleChange} /> **(3)**
</fieldset>
);
}
}
class Calculator extends React.Component {
handleCelsiusChange(value) {
this.setState({scale: 'c', value});
}
render() {
return (
<div>
<TemperatureInput
scale="c"
value={celsius}
onChange={this.handleCelsiusChange} /> **(1)**
</div>
);
}
}
- In
Calculator
,一个名为onChange
传递对该方法的引用handleCelsiusChange
to TemperatureInput
-
this.props.onChange()
in TemperatureInput
现在是参考handleCelsiusChange()
in Calculator
-
onChange={this.handleChange}
是一个事件监听器,它将触发handleChange()
输入字段的更改。
综上所述,onChange
由于道具是定制的,onChange
因为内置了事件侦听器。 prop 只是将函数引用从祖先传递给子级,以便您可以在子级中运行它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)