无法读取属性'道具'未定义的错误

时间:2017-06-03 21:06:01

标签: javascript reactjs

我试图让孩子与父母沟通,所以,我正在使用道具。有一点问题。我使用StatusChanged()函数时出错。

我的父(App.JS)文件:

class App extends Component {

  constructor(props) {
    super(props);
    this.state = { trackingStatus: true };
  }

  trackingStatusUpdate(data)
  {
      console.log(data);
  }

  render() {
    return (
      <div className="App">
        <Switcher trackingStatus={this.state.trackingStatus} trackingStatusUpdate={this.trackingStatusUpdate} />
      </div>
    );
  }
}

还有我的孩子(Switcher.JS)文件:

class Switcher extends Component {


    constructor(props) {
        super(props);
        this.state = {
            trackingStatus: this.props.trackingStatus
        };
    }   


    statusChanged()
    {
        this.props.trackingStatusUpdate(this.state.trackingStatus);
    }

    render() {
        return (
            <div>
                <h3>Tracking Mode</h3>
                <label className="switch">
                  <input type="checkbox" defaultChecked={this.state.trackingStatus} onChange={this.statusChanged}  id="switch"  />
                  <div className="slider round"></div>
                </label>
            </div>
        );
    }

}

Switcher.defaultProps = {
    trackingStatus: true
}

有什么问题?

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要绑定trackingStatusUpdate()statusChanged()类方法...

class App extends Component{
  constructor(props){
    super(props);
    this.state = {trackingStatus: true};

    this.trackingStatusUpdate = this.trackingStatusUpdate.bind(this);
  }

  ...
}

class Switcher extends Component{
  constructor(props){
    super(props);
    this.state = {trackingStatus: this.props.trackingStatus};

    this.statusChanged = this.statusChanged.bind(this);
  }

  ...
}