【发布时间】:2019-05-07 11:34:22
【问题描述】:
我刚刚开始学习 React.js(和 Javascript),我有一个非常基本的问题要问你们。
这是一个小组件的工作示例,它创建了 3 个按钮,每次单击按钮时,其值都会递增。
class Button extends React.Component {
handleClick = () => {
this.props.onClickFunction(this.props.incrementValue);
}
render(){
return(
<button onClick={this.handleClick}>
{this.props.incrementValue}
</button>
);
}
}
const Result = (props) => {
return(
<div>{props.counter}</div>
);
};
class App extends React.Component {
state = {counter: 0};
incrementCounter = (incrementValue) => {
this.setState((prevState) => ({
counter: prevState.counter + incrementValue
}));
};
render() {
return (
<div>
<Button incrementValue={2} onClickFunction={this.incrementCounter}/>
<Button incrementValue={10} onClickFunction={this.incrementCounter}/>
<Button incrementValue={99} onClickFunction={this.incrementCounter}/>
<Result counter={this.state.counter}/>
</div>
);
}
}
ReactDOM.render(<App />, mountNode);
在体验代码时,我尝试更改handleClick函数。
class Button extends React.Component {
handleClick(){
this.props.onClickFunction(this.props.incrementValue);
}
render(){
return(
<button onClick={this.handleClick}>
{this.props.incrementValue}
</button>
);
}
}
const Result = (props) => {
return(
<div>{props.counter}</div>
);
};
class App extends React.Component {
state = {counter: 0};
incrementCounter = (incrementValue) => {
this.setState((prevState) => ({
counter: prevState.counter + incrementValue
}));
};
render() {
return (
<div>
<Button incrementValue={2} onClickFunction={this.incrementCounter}/>
<Button incrementValue={10} onClickFunction={this.incrementCounter}/>
<Button incrementValue={99} onClickFunction={this.incrementCounter}/>
<Result counter={this.state.counter}/>
</div>
);
}
}
ReactDOM.render(<App />, mountNode);
我现在得到:Uncaught TypeError: Cannot read property 'props' of undefined 在句柄点击处(评估在
据我了解,匿名函数 handleClick = () =>... 由于闭包,可以从父级访问道具,但是当我将其替换为类时,为什么魔术会停止方法?
【问题讨论】:
-
handleClick不是匿名函数。这是一个命名函数,命名为handleClick。 -
这与闭包无关,而是与
this的工作方式有关。看看How does the “this” keyword work?、How to access the correctthisinside a callback? 和Unable to access React instance (this) inside event handler。handleClick = () => ...是一个带有箭头函数的类属性。这两部分使得函数内部的this引用组件实例。 -
一般来说是的 :) 但是,类属性是主要用于 React 的实验性功能。
-
从 ES6 类的工作原理开始考虑。您使用的是 github.com/tc39/proposal-class-fields ,它甚至没有标准化。
标签: javascript reactjs closures