2017-09-04 84 views
-1

我通過道具傳遞子組件的函數highlight(),但我在子組件上運行該函數時出現問題。當我登錄this.props到控制檯componentDidMount()我看到它,但當我嘗試調用它不起作用。將函數傳遞給子組件

class Queen extends React.Component { 
    componentDidMount() { 
    console.log('1) The Queen component has mounted!'); 
    this.props.highlight() 
    } 


    render() { 
    return (
     <div> 
     <h2> 
      {this.props.name} 
     </h2> 
     </div> 
    ); 
    } 
} 

class King extends React.Component { 
    constructor(props) { 
    super(props) 

    this.state = { 
     highlighted: false 
    } 
    } 

    componentDidMount() { 
    console.log('2) The King component has mounted!'); 
    } 


    highlight() { 
    this.setState({ 
     highlighted: !this.state.highlighted 
    }) 
    } 

    render() { 
    return (
     <div className="card"> 
     <h1>The King's Queen is...</h1> 
     <Queen 
      name="Amelia" 
      highlight={() => this.highlight.bind(this)} 
      className={this.state.highlighted ? 'highlight' : ''}/> 
     </div> 
    ); 
    } 
} 


ReactDOM.render(<King />, 
       document.querySelector(".wrapper")); 

發生這種情況是因爲Queen組件已經安裝在國王面前,因爲它是兒童組件?試圖把我的頭圍繞在這裏發生的事情,同樣重要的是爲什麼這不起作用。

回答

0

您正在訪問處理程序,而不是僅僅綁定它。

<Queen 
    name="Amelia" 
    highlight={this.highlight.bind(this)} 
    className={this.state.highlighted ? 'highlight' : ''} 
/> 

變本加厲,你可以在構造

class King extends React.Component { 
    constructor(props) { 
    super(props) 

    this.highlight = this.highlight.bind(this) 
    } 

    highlight() { 
    ... 
    } 

    render() { 
    return (
     <div className="card"> 
     <h1>The King's Queen is...</h1> 
     <Queen 
      name="Amelia" 
      highlight={this.highlight} 
      className={this.state.highlighted ? 'highlight' : ''}/> 
     </div> 
    ); 
    } 
} 
+0

啊哈是綁定你的處理器。乾杯! –