在 html 中显示反应 javascript

Displaying react javascript in html

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

 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>

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

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

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

这是一个演示:http://codepen.io/PiotrBerebecki/pen/LRAmBr

选项 2:或者,您可以只调用一个 returns 所需日期的方法,例如 (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')
);

应该是:

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

区别是this.state.dateTwoWeeksAgo

对于您的代码示例,我建议采用这种方法

 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}