gpt4 book ai didi

javascript - 无法从父组件方法访问状态

转载 作者:行者123 更新时间:2023-12-02 23:31:26 25 4
gpt4 key购买 nike

我使用 props 将方法调用传递给其子组件(键盘和按键),但是当我尝试在子组件(按键)中执行该方法时,该方法无法访问原始组件(计算器)状态,返回未定义


class Calculator extends React.Component{
constructor(){
super()
this.state = {
display : "nothing now"
keys : [
{
class: "digit",
label : "0",
id : "zero",
fn : this.setCalculation
}
]
}

this.setCalculation = this.setCalculation.bind(this)
}


setCalculation(){
console.log(this.state.display) // return undefined when I click a Key Component

}

render(){

return(
<div id="calculator">
<Display content={this.state.display}/>
<Keyboard keys={this.state.keys}/>
</div>
)
}
}

class Keyboard extends React.Component{
constructor(props){
super(props)
}

render(){
let keys = this.props.keys.map((v) => {
return <Key data={v}/>
})

return(
<div id="keyboard">{keys}</div>
)
}
}

class Key extends React.Component{
constructor(props){
super(props)
this.execute = this.execute.bind(this)
}

execute(e){
this.props.data.fn(this.props.data.label)
}

render(){
return (
<div className={"key " + this.props.data.class} style={{gridArea : this.props.data.id}} onClick={this.execute}><span>{this.props.data.label}</span></div>
)
}
}


ReactDOM.render(<Calculator />,document.getElementById("app"))

需要返回计算器组件状态值的方法

最佳答案

除了“nothing now”后面忘记的逗号之外,还需要在定义组件状态之前绑定(bind)setCalculation方法。

constructor(props) {
super(props);
this.setCalculation = this.setCalculation.bind(this);
this.state = {
display : "nothing now",
keys : [
{
class: "digit",
label : "0",
id : "zero",
fn : this.setCalculation
},
],
};
}

关于javascript - 无法从父组件方法访问状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56483710/

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