Переход CSS фона на компонент React при нажатии кнопки - PullRequest
0 голосов
/ 12 марта 2020

Я пытаюсь получить переход цвета фона div по центру при каждом нажатии кнопки «Новая цитата» и создании новой цитаты. У меня возникли проблемы с настройкой перехода к этому div. Я хотел бы иметь набор из 5 цветов, в которые div будет переходить по порядку. Может ли это быть массив css цветов? Не уверен как go об этом. Я также не уверен, как связать этот переход с событием нажатия кнопки.

Компонент кнопки:

class Button extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showComponent: true,
      cardColor: true,
      backgroundColor: true
    };
    this.onButtonClick = this.onButtonClick.bind(this);
  }
  onButtonClick() {
    this.setState({
      showComponent: true,
      cardColor: true,
      backgroundColor: true
    });
  }
  render(){
    return(
    <div>
    <button onClick={this.onButtonClick} type='button' class='btn btn-primary' 
    style={{
      position: 'absolute',
      right: '10px',
      bottom: '10px',
      padding: '2%'
    }}>New Quote</button>
    {this.state.showComponent ? <AuthorQuotePrint props={QUOTES}/> : null}
    </div>
    )
  }
}

Цитата Box Div:

class RandomQuoteBox extends React.Component{
    render(){
      const myStyle={
        backgroundColor: 'red',
                  width: '500px',
                  height: '300px',
                  margin: '0 auto'
      };
      return(
        <div class="container">
            <div class="row">
              <div class="col">
              </div>
              <div class="col-8">
                  <div class="card" style={myStyle}> 
                    <div>
                      <Button />
                    </div>
                  </div>
                </div>
              <div class="col">
                </div>
            </div>
          </div>
        );
    }
}

1 Ответ

1 голос
/ 12 марта 2020

Я предполагаю, что в дальнейшем компоненты <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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...