document.getElementById()。innerHTML没有在ReactJS中获取文本

时间:2015-11-04 15:21:24

标签: javascript reactjs

我通过名为renderToday()的函数渲染了日期。我想得到约会的原因是,我可以离开,或者从那个日期开始。我需要相应地更改日期。

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

我尝试使用document.getElementById('date'),并将div设置为ID为“date”,我使用了.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>
    );
  }
 });

1 个答案:

答案 0 :(得分: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