我刚刚开始学习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);
我现在得到:未捕获TypeError:无法读取未在handleClick定义的属性'props‘(eval at
据我所知,匿名函数handleClick = () =>...因为闭包,所以可以从父类访问属性,但是为什么当我用类方法替换它时,魔术就停止了呢?
https://stackoverflow.com/questions/53640089
复制相似问题