Я передаю вызов метода своим дочерним компонентам (клавиатура и ключ) с помощью реквизита, но когда я пытаюсь выполнить метод в дочернем элементе (ключ), метод не может получить доступ к состоянию исходного компонента (калькулятор), возвращая неопределенное
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.info(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 [JS]](https://i.imgur.com/WsjO6zJb.png)


В дополнение к запятой, которую вы забыли после «ничего сейчас», вам нужно привязать метод 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
},
],
};
}
в примере я хочу напечатать значение состояния, а не возвращать ничего, как сказано. SO не позволяет мне редактировать сообщение.