在html中显示反应javascript

时间:2016-10-13 08:24:57

标签: javascript html reactjs display

我有这个功能设置两周前的日期:

 dateTwoWeeksAgo: function(){
    var twoWeeksAgo = new Date().toDateString();
    this.setState({twoWeeksAgo: twoWeeksAgo});
  },

我有这个调用此函数的代码。但它没有用。如何显示变量我正在设置函数的状态或从函数返回?

<h2 className="headings" id="commitTotal"> Commits since {this.dateTwoWeeksAgo} : {this.state.commits.length} </h2>

3 个答案:

答案 0 :(得分:0)

选项1 :为了显示您所持有的twoWeeksAgo的值,您可以:

<h2 className="headings" id="commitTotal"> Commits since {this.state.twoWeeksAgo} : {this.state.commits.length} </h2>

更新状态的实际方法 - dateTwoWeeksAgo() - 可以在componendDidMount生命周期方法中调用。
https://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount

以下是演示:http://codepen.io/PiotrBerebecki/pen/LRAmBr

选项2 :或者,您可以调用一个返回所需日期的方法(http://codepen.io/PiotrBerebecki/pen/NRzzaX),

const App = React.createClass({
  getInitialState: function() {
    return {
      commits: ['One', 'Two']
    };
  },

  dateTwoWeeksAgo: function() {
    return new Date().toDateString();
  },

  render: function() {
    return (
      <div>
        <h2 className="headings" id="commitTotal"> Commits since {this.dateTwoWeeksAgo()} : {this.state.commits.length} </h2>
      </div>
    );
  }
})

代码选项1:

const App = React.createClass({
  getInitialState: function() {
    return {
      twoWeeksAgo: null,
      commits: ['One', 'Two']
    };
  },

  componentDidMount: function() {
    this.dateTwoWeeksAgo();
  },

  dateTwoWeeksAgo: function() {
    var twoWeeksAgo = new Date().toDateString();
    this.setState({twoWeeksAgo: twoWeeksAgo});
  },

  render: function() {
    return (
      <div>
        <h2 className="headings" id="commitTotal"> Commits since {this.state.twoWeeksAgo} : {this.state.commits.length} </h2>
      </div>
    );
  }
})

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

答案 1 :(得分:0)

应该是:

<h2 className="headings" id="commitTotal"> Commits since {this.state.dateTwoWeeksAgo} : {this.state.commits.length} </h2>

差异为this.state.dateTwoWeeksAgo

答案 2 :(得分:0)

对于您的代码示例,我建议使用此方法

 dateTwoWeeksAgo: function(){
    return new Date().toDateString();
  },

<h2 className="headings" id="commitTotal"> Commits since {this.dateTwoWeeksAgo()} : {this.state.commits.length} </h2>

如果您真的想使用州,则需要更改{this.dateTwoWeeksAgo} to {this.state.dateTwoWeeksAgo}