簡體   English   中英

如何訪問 React 組件內部的數組?

[英]How to access a array inside of a React component?

所以,我正在做這個簡短的 freecodecamp 前端項目,其中將生成一個隨機報價,如果您單擊“新報價”按鈕,它將生成一個隨機報價。 所以我在 react 組件之外聲明了這個隨機引用,

const randomQuotes = [{"quote": "Life isn’t about getting and having, it’s about giving and being.", "author": "Kevin Kruse"},
{"quote": "Whatever the mind of man can conceive and believe, it can achieve.", "author": "Napoleon Hill"}]

我的反應組件是

class MyComponent extends React.Component{
  constructor(props){
    super(props)
    this.state = {   //this is just an example
      quote:'wow', 
      author:'wow2'
    }
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick(){
    this.setState({
      quote:'you clicked',
      author:'new one'
    })
  }
  render(){
    return(
      <div id="quote-box">
    <div id='text'>
      <h1 class='text-center'>{this.state.quote}</h1> //randomly generated quote will be shown here
    </div>
    <div id='author'>
      <h1 class='text-center'>{this.state.author}</h1>  //the author of the randomly generated quote will be shown here
    </div>
    <div class='row'>
      <div class='col-xs-4'>
        <button id="new-quote" class='btn btn-primary btn-block' onClick={this.handleClick}>New Quote</button>
           </div>
       <div class='col-xs-6'>
         <a id='tweet-quote' href='twitter.com/intent/tweet'>tweet</a>
      </div>
    
    </div>
   
  </div>
    )
  }
}
ReactDOM.render(<MyComponent/>, document.getElementById('quote-box'));

我的問題是,如何訪問已全局聲明的數組? 我應該創建一個新的子組件並將這個數組作為道具傳遞嗎? 或者有沒有其他方法可以做到這一點?

這個數組似乎是靜態的,所以你可以像下面這樣導出它......

randomQuotes.js

export const randomQuotes = [{"quote": "Life isn’t about getting and having, it’s about giving and being.", "author": "Kevin Kruse"},
{"quote": "Whatever the mind of man can conceive and believe, it can achieve.", "author": "Napoleon Hill"}]

...然后將其導入到您的組件文件中:

我的組件.js

import { randomQuotes } from 'path/to/randomQuotes.js'

class MyComponent extends React.Component{
   ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM