我试图从官方 react 文档中理解这段代码:
https://codepen.io/gaearon/pen/WZpxpz?editors=0010
class TemperatureInput extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.onTemperatureChange(e.target.value);
}
render() {
const temperature = this.props.temperature;
const scale = this.props.scale;
return (
<fieldset>
<legend>Enter temperature in {scaleNames[scale]}:</legend>
<input value={temperature}
onChange={this.handleChange} />
</fieldset>
);
}
}
class Calculator extends React.Component {
constructor(props) {
super(props);
this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
this.state = {temperature: '', scale: 'c'};
}
handleCelsiusChange(temperature) {
this.setState({scale: 'c', temperature});
}
handleFahrenheitChange(temperature) {
this.setState({scale: 'f', temperature});
}
render() {
const scale = this.state.scale;
const temperature = this.state.temperature;
const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;
return (
<div>
<TemperatureInput
scale="c"
temperature={celsius}
onTemperatureChange={this.handleCelsiusChange} />
<TemperatureInput
scale="f"
temperature={fahrenheit}
onTemperatureChange={this.handleFahrenheitChange} />
<BoilingVerdict
celsius={parseFloat(celsius)} />
</div>
);
}
}
输入更改时,我们调用 this.props.onTemperatureChange(e.target.value)
。
这个函数调用如何在父组件的上下文中执行?
纯 JavaScript 中的等效行为是什么?
是不是这样,当我们在 props 中传递父组件的函数时,该函数(即 handleCelsiusChange
)会绑定(bind)到父组件 ((this.handleCelsiusChange.bind(this )
),无论我们在哪里执行它,它仍然会在它自己的上下文中进行更改?
如果我的描述不准确,请纠正我。
最佳答案
正如@Farhan Tahir
和@Harsh kurra
所指出的,您正在以正确的方式理解它。也许他们已经回答了您有关 React 工作和事件传播到父级的问题。那么,我将讨论第二部分——用纯 JavaScript 来做。
我使用构造函数模式在 Vanilla JS 中实现了一个简单的示例。请看下面的代码来理解。
// Writing Constructors for Parent and Child.
function Parent(name) {
this.name = name;
this.changeName = function(newName) {
this.name = newName;
};
}
function Child(changeName) {
this.changeName = changeName;
}
// Creating instances and testing.
let p1 = new Parent('foo');
console.log(p1.name); // It will print 'foo'.
// Pass it to child and bind.
let c1 = new Child(p1.changeName.bind(p1));
c1.changeName('bar');
console.log(p1.name); // It will print 'bar'.
这就是幕后发生的事情。 React 有进一步的实现来反射(reflect)组件和其他内容的更改。
关于javascript - 在 React 中,子组件如何调用在其父组件上下文中执行的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57177010/