gpt4 book ai didi

javascript - 如何绑定(bind)方法

转载 作者:行者123 更新时间:2023-12-03 03:53:32 25 4
gpt4 key购买 nike

我正在尝试创建一个计数器按钮,但我做不到。我知道这与绑定(bind)有关,但我找不到解决方案。我尝试使用 .bind(this) 但它不起作用。

class Button extends React.Component{
render(){
return(
<button onClick={this.props.localHandleClick}>+1</button>
)
}
}
class Result extends React.Component{
render(){
return (
<div>{this.props.localCounter}</div>
)

}
}
class Main extends React.Component{
constructor(props){
super(props);
this.state={
counter:0
}
}
clickHandler(){
this.setState({counter:
this.state.counter+1});
}
render(){
return(
<div>
<Button localHandleClick={this.handleClick}/>
<Result localCounter={this.state.counter} />
</div>
)

}
}
ReactDOM.render(
<Main />,
document.getElementById("app")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

最佳答案

变化:

1.在主组件的构造函数中绑定(bind)handleClick方法。

2. 名称不匹配,您正在传递 handleClick 方法,但定义了 clickHandler。将 clickHandler 替换为 handleClick

检查工作片段:

class Button extends React.Component{
render(){
return(
<button onClick={this.props.localHandleClick}>+1</button>
)
}
}

class Result extends React.Component{
render(){
return (
<div>{this.props.localCounter}</div>
)

}
}

class Main extends React.Component{
constructor(props){
super(props);
this.state={
counter:0
}
this.handleClick = this.handleClick.bind(this);
}

handleClick(){
this.setState({counter: this.state.counter+1});
}

render(){
return(
<div>
<Button localHandleClick={this.handleClick}/>
<Result localCounter={this.state.counter} />
</div>
)

}
}

ReactDOM.render(
<Main />,
document.getElementById("app")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

关于javascript - 如何绑定(bind)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45066399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com