我对尝试理解react如何与作为props的功能一起工作,并将它们传递给子组件感到怀疑。我已经看过一些教程,但目前还不了解我的问题。
基本上,我有一个简单的组件可以向下传递列表,而其他组件则可以使用Array.map处理该列表以呈现另一个组件。
基本上我有以下几点:
App.js->报价->报价。
我想处理对Quote组件的单击。因此,每当用户单击Quote时,我都希望在APP.js上处理它。
我已经尝试过将引用作为道具传递下来,并在app.js引号组件中调用该函数,但这没有用。
这是我到目前为止尝试过的:
App.js
import React, { Component } from 'react';
import classes from './App.module.css';
import Quotes from '../components/quotes/quotes'
class App extends Component {
state = {
quotes: [
{ id: 1, text: "Hello There 1" },
{ id: 2, text: "Hello There 2" },
{ id: 3, text: "Hello There 3" },
{ id: 4, text: "Hello There 4" }
],
clickedQuote: "none"
}
handleClickedQuote (id) {
console.log(id)
const quoteIndex = this.state.quotes.findIndex(q => q.id === id)
this.setState({
clickedQuote: this.state.quotes[quoteIndex].text
})
}
render() {
return (
<div className="App">
<div className={classes['quotes-wrapper']}>
<Quotes clicked={this.handleClickedQuote} quotes={this.state.quotes}/>
<p>clicked quote {this.state.clickedQuote}</p>
</div>
</div>
);
}
}
export default App;
Quotes.js
import React from 'react';
import Quote from './quote/quote'
const quotes = (props) => props.quotes.map((quote) => {
return (
<Quote clicked={props.clicked} text={quote.text}/>
)
})
export default quotes
Quote.js
import React from 'react';
import classes from './quote.module.css'
const quote = (props) => {
return (
<div onClick={() => props.clicked(props.id)} className={classes.quote}>
<p className={classes['quote-text']}>{props.text}</p>
</div>
)
}
export default quote
我需要在App.js函数的hanleClickedQuote上获取ID。我究竟做错了什么?
守候你守候我
相关分类