类型错误:无法读取属性“道具”空的反应

问题描述:

错误: 未捕获的类型错误:(:75:17)在babaClick无法读取空 的属性“道具” 在ES5如果i型它也不会是错了,但如果我在ES6就像下面的代码键入这是错的。我只是不知道为什么...类型错误:无法读取属性“道具”空的反应

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<title>HelloMessage</title> 
<script src="lib/react.js"></script> 
<script src="lib/react-dom.js"></script> 
<script src="lib/babel.min.js"></script> 
<script type="text/babel"> 
    class HelloMesssage extends React.Component{ 
     constructor(props){ 
      super(props) 
      this.state={ 
       zan:0 
      } 

     } 
     addZan(){ 
      this.setState(
        { 
         zan:this.state.zan+1 
        } 
      ) 
     } 
     render(){ 
      return(
        <div> 
         <p>姓名:{this.props.name}</p> 
         <p>赞:<Zan zan={this.state.zan}/></p> 
         <p><Btn babaZan={this.addZan.bind(this)}/></p> 
        </div> 
      ) 
     } 
    } 
    class Btn extends React.Component{ 
     babaClick(){ 
      this.props.babaZan(); 
     } 
     render(){ 
      return(
        <button onClick={this.babaClick}>赞</button> 
      ) 
     } 

    } 
    class Zan extends React.Component{ 
     render(){ 
      return(
        <span>{this.props.zan}</span> 
      ) 
     } 
    } 
    ReactDOM.render(
      <HelloMesssage name="xxxindy"/>, 
      document.getElementById('container') 
    ); 
</script> 
<div id="container"></div> 

在你Btn类,则应该像HelloMesssage类(如babaZan={this.addZan.bind(this)})中那样,使用onClick处理程序添加.bind(this)

因此,onClick将变成如下所示的onClick={this.babaClick.bind(this)}

:在ES6,它需要.bind(this)而在ES5,这不是必需的。

class Btn extends React.Component{ 
     babaClick(){ 
      this.props.babaZan(); 
     } 
     render(){ 
      return(
        <button onClick={this.babaClick.bind(this)}>赞</button> 
      ) 
     } 

    } 
+0

感谢üSOOOO多!有用!!!!我的眼睛充满了泪水! – xxxindy

变化babaClick(){ this.props.babaZan(); }到箭头的功能,以便它知道什么“本”是:babaClick =() => { this.props.babaZan(); }

+0

是的,它的工作原理!非常感谢你!! – xxxindy