【发布时间】:2019-06-06 19:10:34
【问题描述】:
我正在使用道具将方法调用传递给其子组件(键盘和键),但是当我尝试在子组件(键)中执行该方法时,该方法无法访问原始组件(计算器)状态, 返回未定义
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"))
需要返回计算器组件状态值的方法
【问题讨论】:
-
在示例中我想打印状态值,而不是返回任何内容。所以不允许我编辑帖子。
标签: javascript reactjs