【问题标题】:Displaying react javascript in html在 html 中显示 react javascript
【发布时间】:2016-10-13 17:21:19
【问题描述】:

我有这个函数可以设置两周前的日期:

 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>

【问题讨论】:

  • 你能分享完整的组件代码吗?
  • 您还想看什么?粘贴整个文件会太大。在我设置状态后,肯定有一种简单的方法来显示数据吗?

标签: javascript html reactjs display


【解决方案1】:

选项 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:或者,您可以像这样调用返回所需日期的方法 (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')
);

【讨论】:

  • 由于某种原因无法正常工作。我必须把它放在里面吗didMount?
  • 酷,这行得通。那么组件确实挂载有什么重要的呢?
  • componentDidMount() 是一个内置的 React '生命周期方法'。它在你的组件被渲染后被 React 调用一次。例如,这是进行 AJAX 调用的地方。我刚刚添加了一个指向 React 文档的链接,您可以在其中了解更多信息。您希望我在上面添加任何内容还是回答您的问题?
  • 我刚刚为您的问题添加了第二个解决方案。请查看选项 2 的 codepen 链接。这样可以避免使用状态来保持日期。
【解决方案2】:

应该是:

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

区别是this.state.dateTwoWeeksAgo

【讨论】:

  • 这也是我的想法,但它只是返回空白,没有错误
【解决方案3】:

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

 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}

【讨论】:

  • 这也是我的想法,但它只是返回空白,没有错误
猜你喜欢
  • 1970-01-01
  • 2021-12-04
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-18
  • 2020-01-16
相关资源
最近更新 更多