2015-11-04 54 views
1

我通過一個名爲renderToday()的函數呈現日期。我想得到約會的原因是,我可以離開那天,也可以離開那天。我需要相應地更改日期。document.getElementById()。innerHTML在ReactJS中沒有獲取文本

renderToday: function() { 
    var today = new Date(); 
    return today.toDateString(); 
    }, 

我試着用document.getElementById('date'),我設置div與「日期」的ID,我用.innerHTML。現在,所有在AccountsUIWrapper下的東西都不會顯示出來。

renderMoods() { 
    // Get tasks from this.data.moods 
    var d = document.getElementById("date"); 
    return (<div>{d.innerHTML}</div>); 
}, 

render: function() { 
    return (
     <div className="container"> 
     <h1>How are You?</h1> 
     <AccountsUIWrapper /> 

     { this.data.currentUser ? 
     <div> 
     <form className="your_mood" onSubmit={this.handleSubmit} > 
      <select ref="mood"> 
      <option value="0" disabled selected>Select your Mood</option> 
      <option value=":)">:)</option> 
      <option value=":|">:|</option> 
      <option value=":(">:(</option> 
      </select> 
      <button type="submit">submit</button> 

     </form> 

     <div id="date"> 
      {this.renderToday()} 
     </div> 
     <div> 
      {this.renderMoods()} 
     </div> 
     </div> 
     : '' 
     } 

     </div> 
    ); 
    } 
}); 
+0

*'的document.getElementById()''錯字的document.getElementById()' – rajuGT

+1

@rajuGT人!閱讀代碼,而不是標題!這篇文章的標題是非常錯誤的,但代碼不是 –

+1

你的控制檯是否有錯誤? – taxicala

回答

0

這是因爲你是從DOM在時間試圖獲取元素時DOM沒有準備好,你可以叫renderToday()renderMoods()

var Component = React.createClass({ 
    renderToday() { 
     return Date.now(); 
    }, 

    renderMoods() { 
     return <h2> 
      { this.renderToday() } 
     </h2>; 
    }, 

    render() { 
     return <div> 
      <h1>Component</h1> 
      <div>{ this.renderToday() }</div> 
      <div>{ this.renderMoods() }</div> 
     </div>; 
    } 
}); 

Example

您可以撥打DOM操作componentDidMount處理程序,閱讀更多關於component lifecycle - 它是可能的但不建議

var Component = React.createClass({ 
    renderToday() { 
     return Date.now(); 
    }, 

    componentDidMount() { 
     document.getElementById('mood').innerHTML = document.getElementById('date').innerHTML 
    }, 

    render() { 
     return <div> 
      <h1>Component</h1> 
      <div id="date">{ this.renderToday() }</div> 
      <div id="mood"></div> 
     </div>; 
    } 
}); 

Example

+1

很好的解釋! +1 – wintvelt

相關問題