2016-11-08 73 views
0

我有這樣一段代碼陣營克隆兒童及附加道具不工作

render() { 
    const { schools, currentSchool, claims } = this.state; 
    let loggedIn = this.state.loggedIn ? true : false; 
    let user = this.state.user; 

     var children = React.Children.map(this.props.children, function (child) { 
     return React.cloneElement(child, { 
      **claims: this.state.claims** 
      }) 
    }) 
    return (
     <div> 
     <HeaderContainer 
      user={user} 
      claims={claims} 
      onLogin={this.onLoginButtonClick} /> 

     { loggedIn && <NavContainer claims={claims}/> } 

      {children}  

     <Footer/> 
     </div> 
    ) 
    } 
    } 

但是我沒有訪問this.state.claims由於某種原因,「本」是不確定的。爲什麼是這樣的,我該如何解決這個問題?

+0

基本javascript es6,這與reactjs無關。使用胖箭頭功能來保持'this'上下文。所以在你的'React.Children.map'中,你需要使用'(child)=> {}'而不是'function(child){}'。更多這裏:http://exploringjs.com/es6/ch_arrow-functions.html –

回答

-1

有2種方法可以達到這個人是在渲染功能使用該=這個 let that = this; 然後在函數,而不是使用this.state.claims:

return React.cloneElement(child, {//use that variable here }) 

或其他方式,你可以實現,這是通過使用箭頭函數

var children = this.props.children.map(child => { return React.cloneElement(child, { **claims: this.state.claims** })

JavaScript是所有關於範圍和在JavaScript是函數作用域確定不會阻止範圍的變量。在javascript中閱讀更多關於範圍。