2015-11-04 390 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

相关问题