Я предполагаю, что в дальнейшем компоненты <RandomQuoteBox />
и <Button />
имеют общего родителя.
С этим вы можете прикрепить событие onClick
в компоненте <Button />
к обратному вызову в общем родительском элементе (например, <QuoteForm />
), которая изменяет родительскую переменную состояния, соответствующую текущему применяемому цветовому индексу, в пределах <RandomQuoteBox />
Рассмотрим приведенную ниже демонстрационную программу, которую я пытался адаптировать к вашему варианту использования и в то же время пытался сохранить дистилляцию:
const { render } = ReactDOM,
rootNode = document.getElementById('root')
class AuthorQuotePrint extends React.Component {
render(){
return <div>{this.props.quote}</div>
}
}
class Button extends React.Component {
render(){
return(
<div>
<button onClick={this.props.onNextQuote}>Next Quote</button>
<AuthorQuotePrint quote={this.props.quote} />
</div>
)
}
}
class RandomQuoteBox extends React.Component {
constructor(props){
super(props)
this.state = {
quotes: ['Some quote', 'Some other quote', 'Just one more quote', 'Yet another quote', 'This one is quote too'],
colors: ['red', 'green', 'blue', 'purple', 'black']
}
this.state = {
...this.state,
currentQuoteIdx: Math.random()*this.state.quotes.length|0,
currentColorIdx: 0
}
this.onNextQuote = this.onNextQuote.bind(this)
}
onNextQuote(){
const nextQuoteIdxShift = 0|Math.random()*this.state.quotes.length || 1,
nextQuoteIdx = (this.state.currentQuoteIdx+nextQuoteIdxShift)%this.state.quotes.length
this.setState({
currentQuoteIdx: nextQuoteIdx,
currentColorIdx: (this.state.currentColorIdx+1)%this.state.colors.length
})
}
render(){
return(
<div
style={{
backgroundColor:this.state.colors[this.state.currentColorIdx],
color: '#fff',
width: 200
}}
>
<Button
onNextQuote={this.onNextQuote}
quote={this.state.quotes[this.state.currentQuoteIdx]}
/>
</div>
)
}
}
render(<RandomQuoteBox />, rootNode)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>