【发布时间】:2021-02-15 08:03:51
【问题描述】:
所以,我正在做这个简短的 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'));
我的问题是,如何访问已全局声明的数组?我应该创建一个新的子组件并将这个数组作为道具传递吗?还是有其他方法可以做到这一点?
【问题讨论】:
-
您可以通过将其作为道具传递来在第一个组件中访问它,无需创建另一个子组件。但是,您需要对其进行映射以查看其中的所有数据。这就是你想要达到的目标吗?
-
@CyberMessiah 当页面第一次重新加载时应该有一个引用,然后应该有一个随机引用,该引用将从数组中生成。我该怎么办?我认为我不需要地图来显示所有数据。
-
我明白了。然后应该有从数组中获取特定项目的逻辑。例如,您可以将其放在您的 handleClick 函数中。您可以为此使用过滤器。 upmostly.com/tutorials/…会给你一些线索。
标签: javascript html css reactjs frontend