简体   繁体   English

如何访问 React 组件内部的数组?

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

So, I am doing this short freecodecamp frontend project, where a random quote will generate and if you click "new quote" button, it will generate a random quote.所以,我正在做这个简短的 freecodecamp 前端项目,其中将生成一个随机报价,如果您单击“新报价”按钮,它将生成一个随机报价。 So I have declared this random quote outside the react component,所以我在 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"}]

And my react component is我的反应组件是

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'));

My question is, how to access the array which has been globally declared?我的问题是,如何访问已全局声明的数组? should I create a new child component and pass this array as props?我应该创建一个新的子组件并将这个数组作为道具传递吗? or is there any other way to do this?或者有没有其他方法可以做到这一点?

This array seems to be static so you can just export it like the following...这个数组似乎是静态的,所以你可以像下面这样导出它......

randomQuotes.js 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"}]

...and then import it in your component file: ...然后将其导入到您的组件文件中:

MyComponent.js我的组件.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