React Child prop 变量未定义,即使我之前定义了变量

React Child prop variable is undefined even though I defined the variable before

所以我想显示 persons.In 我的 parent 组件 mappersonarray 的列表。每个人都有姓名、名字和年龄。 显示具有所有属性的每个人都没有问题,但我在 "r" 上有一个键绑定,如果我稍后在键盘上按 "r",我想控制台记录一个特定人的年龄。这就是我在 Person 组件中定义按键功能的原因。但是现在如果我在键盘上按 "r",我会收到以下错误:“TypeError: Cannot read property 'person' of undefined”在我试图控制台记录年龄为 his/her 的人的行。

这基本上是我的 Parent class(PersonList.js):

{ personList.map((person, index) => {       //mapping a person list (e.g. 5 persons with 
                                            //name,firstname and age for each enty

          let active= this.state.activePerson    //true if person is active, else: false
           return (
                    <Person person={person} index={index} active={active}/>
                  )

})}

这是我的 child 组件 (Person.js):

export default class Person extends Component {

constructor(props) {
    super(props);
    this.state = {
        active: false,
        person: this.props.person,
    };
}
componentWillReceiveProps(nextProps) {
    this.setState({ active: nextProps.active });
}

componentWillMount() {
    document.addEventListener("keydown", this.onKeyPressed, false);
}

componentWillUnmount() {
    document.removeEventListener("keydown", this.onKeyPressed, false);
}

onKeyPressed(e) {
    const keyCode = e.keyCode

    if (keyCode === 82) {  //if I press r on the keyboard, the name of the active person should be 
                           //displayed (I set the attribute active to true if I click on the person 
                           //card)

        console.log("the person "+ this.state.person.name+ "is" + this.state.person.age)
    }
}

render() {
    return (

           <Card className={this.state.active}>
                {this.state.person.name}
                {this.state.person.firstname}
                {this.state.person.name}
           </Card>

所以每张卡片都能正确显示,但如果我按 "r",我会得到 TypeError: Cannot read property 'person' of undefined。我在 Whosebug 上找不到关于这个问题的任何信息。希望任何人都可以帮助我。

干杯:-)

您的构造函数应如下所示

constructor(props) {
  super(props);
  this.state = {
    active: false,
    person: props.person,
  };
}

你没有绑定你的函数。使用箭头函数或将 this.onKeyPressed = this.onKeyPressed.bind(this); 添加到构造函数中。

"This" 在您的 "onKeyPressed" 处理函数

中不可用

绑定事件或使用箭头函数

document.addEventListener("keydown", this.onKeyPressed.bind(这​​个), false);

onKeyPressed = e => {
const keyCode = e.keyCode;

if (keyCode === 82) {
  //if I press r on the keyboard, the name of the active person should be
  //displayed (I set the attribute active to true if I click on the person
  //card)

  console.log(
    "the person " + this.state.person.name + "is" + this.state.person.age
  );
}

};