【发布时间】:2019-10-27 11:47:40
【问题描述】:
// Child component
class Button extends React.Component {
render() {
console.log("Render of Button called");
return (
<button onClick={this.props.handleClick}>
{this.props.children}
</button>
);
}
}
// Parent component
class ButtonRenderer extends React.Component {
state = {
count: 0
};
increment() {
this.setState({
count: this.state.count + 1
});
}
render() {
console.log("Render of ButtonRenderer called.");
return (
<div>
<Button handleClick={this.increment.bind(this)}>Click me</Button>
<div>Count: {this.state.count}</div>
</div>
);
}
}
function init() {
var rootElement = document.getElementById("root");
const childElement = <ButtonRenderer />;
ReactDOM.render(childElement, rootElement);
}
对于按钮的每次点击,父组件的状态都会发生变化,因此 ButtonRenderer.render 将与子组件 Button.render 一起被调用。 为什么?
我尝试了所有 3 种调用事件处理程序的方法:
使用内联绑定()。和上面的代码一样。
类属性:
...
increment = () => {
this.setState({
count: ++this.state.count
});
}
...
<Button handleClick={this.increment}>Click me</Button>
...
- 内嵌箭头函数。
...
increment(){
this.setState({
count: ++this.state.count
});
}
...
<Button handleClick={() => {this.increment();}}>Click me</Button>
...
对于每次点击,所有 3 种方法都会执行两种渲染方法。
我希望方法 1 和方法 2 不会为每次点击调用 Button 的渲染方法,因为没有任何改变。我希望方法 3 为每次点击调用 Button 的渲染方法,因为我正在使用内联箭头函数,该函数将为 ButtonRendered 类的每个渲染创建一个新函数。
每次点击按钮的浏览器控制台输出:
Render of ButtonRenderer called.
Render of Button called
我的问题:当没有专业人士更改为 Button comp 时,为什么甚至方法 1(使用绑定)和方法 2(使用类属性)都调用子组件 Button 的 render() 方法?
【问题讨论】:
标签: javascript reactjs