Javascript 如何访问React组件内部的阵列?
所以,我正在做这个简短的freecodecamp前端项目,其中将生成一个随机报价,如果您单击“new quote”按钮,它将生成一个随机报价。 所以我在react组件之外声明了这个随机引用Javascript 如何访问React组件内部的阵列?,javascript,html,css,reactjs,frontend,Javascript,Html,Css,Reactjs,Frontend,所以,我正在做这个简短的freecodecamp前端项目,其中将生成一个随机报价,如果您单击“new quote”按钮,它将生成一个随机报价。 所以我在react组件之外声明了这个随机引用 const randomQuotes = [{"quote": "Life isn’t about getting and having, it’s about giving and being.", "author": "Kevin Kr
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'));
类MyComponent扩展了React.Component{
建造师(道具){
超级(道具)
this.state={//这只是一个示例
引用:哇,
作者:'wow2'
}
this.handleClick=this.handleClick.bind(this)
}
handleClick(){
这是我的国家({
引用:'你点击了',
作者:《新的》
})
}
render(){
返回(
{this.state.quote}//此处将显示随机生成的引号
{this.state.author}//此处将显示随机生成的引号的作者
新报价
)
}
}
ReactDOM.render(,document.getElementById('quote-box');
我的问题是,如何访问已全局声明的数组?我应该创建一个新的子组件并将此数组作为道具传递吗?或者有其他方法可以做到这一点吗?此数组似乎是静态的,因此您可以按如下方式导出它 randomQuotes.js
export-const-randomQuotes=[{“quote”:“生活不是获得和拥有,而是给予和存在。”,“作者”:“Kevin Kruse”},
{“引文”:“人的思想能够设想和相信什么,它就能够实现。”,“作者”:“拿破仑·希尔”}]
…然后将其导入组件文件:
MyComponent.js
从'path/to/randomQuotes.js'导入{randomQuotes}
类MyComponent扩展了React.Component{
...
您可以通过将其作为道具传递到第一个组件中来访问它,无需创建另一个子组件。但是,您需要映射它以查看其中的所有数据。这就是您试图实现的吗?@CyberMessiah嗯,当页面首次重新加载时,应该有一个引号,然后应该有一个随机引号,它将在rom数组。我应该怎么做?我不认为我需要映射来显示所有数据。我明白了。然后应该有逻辑从数组中获取特定项。例如,你可以将其放入handleClick函数中。你可以为此使用筛选器。这会给你一些线索。