В Codepen, как вы импортируете компонент React из одного пера в другой? - PullRequest
0 голосов
/ 10 мая 2018

У меня есть две ручки, и я пытаюсь использовать компонент React, который я определил в одной ручке внутри другой, но я не совсем понимаю, как Codepen обрабатывает импорт React между ручками. Я подошел к перу назначения и добавил адрес исходного пера в ссылки Javascript, но я не знаю, как поступить дальше. Я могу заставить это работать в проекте локального узла с использованием традиционного экспорта, но элемент Codepen доставляет мне проблемы. Вот код:

ИСТОЧНИК (https://codepen.io/ejpg/pen/LmOVoR):

export default class Wheel extends React.Component // Export default causes error
{
  constructor(props){
    super(props);

    this.state = {
      spin : false,
      value: 0
    };
    this.spin = this.spin.bind(this);
  }

  spin(e){

    var val = this.state.value + 720 + (Math.floor(Math.random() * 24) * 15);
    console.log((this.state.value % 360) / 15);
    e.target.style.webkitTransform = 'rotate(' + -val + 'deg)';
    e.target.style.webkitTransition = '-webkit-transform 4s ease-out';
    this.setState({value: val});
  }
  render(){
    const wheelVals = [800, "BANKRUPT", 200, 300, 350, 250, 400, 300, 200, 250, 500, 350, 250,
                      "BANKRUPT", 200, 300, 400, 250, 600, "LOSE A TURN", 200, 300, 250, 200];
    return (<div><img width="400" height="400" src="https://orig00.deviantart.net/0a38/f/2010/242/f/6/singapore_wheel_of_fortune_by_wheelgenius-d2xmb9v.jpg" onClick={(e) => this.spin(e)}/><br/><br/>{wheelVals[(this.state.value % 360) / 15]}
</div>);

  }
}

DESTINATION (https://codepen.io/ejpg/pen/bMgWpN):

let { Grid, Row, Col, ButtonToolbar, Button } = ReactBootstrap;
// How do I import the class?
class CustomButton extends React.Component {
  onHandleClick = () => {
    this.props.onClick();
  };

  render(){

    return <Button bsStyle={this.props.bsStyle} onClick={this.onHandleClick}><strong>{this.props.text}</strong></Button>;

  }

}

class Letter extends React.Component {
  onHandleClick = () => {
    this.props.onClick(this.props.letter);
  };

  render () {
    const style = { border: '1px solid black',
                display: 'inline-block',
                fontSize: '3.5vw',
                width: '4vw',
                height: '10vh',
                textAlign: 'center',
                  whiteSpace: 'no-wrap',
                  overflow: 'hidden'};

    if (this.props.letter === ' ') style.border = '';
    return (

      <div 
        style={style} 
        key={this.props.key} 
        onClick={this.onHandleClick} // Have to pass onClick to div
      >
        {this.props.letter}
      </div>
    );
  }
}

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    var blanks = '';

    for (var i = 0; i < this.props.answer.length; ++i)
    {
      this.props.answer[i] === ' ' ?
        blanks += ' ': blanks += '-';

    }

    this.state = {
      phrase: blanks,
      alpha: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
      bonus: false,
      revealed: false
    };
    this.callLetter = this.callLetter.bind(this);
    this.bonusRound = this.bonusRound.bind(this);
    this.complete = this.complete.bind(this);
  }

  replaceAt(str, index, replacement) {
    return str.substr(0, index) + replacement + str.substr(index + replacement.length);
  }

  complete(){
    if (this.state.revealed === false)
    {
      this.setState({phrase: this.props.answer, revealed: true});


    }

  }
  checkForLetter(letter, phr)
  {

    this.setState((prevState, props) => {

      var prephrase = prevState.phrase;
      var index = phr.indexOf(letter);

      while( index !== -1)
      {
        prephrase = this.replaceAt(prephrase, index, letter);
        index = phr.indexOf(letter, index + 1);

      }
      return ({phrase: prephrase});
    });

  }

  callLetter(letter) {

    this.setState((prevState, props) => {
      var alphaclone = prevState.alpha;
      var letterindex = alphaclone.indexOf(letter);

      alphaclone = alphaclone.slice(0, letterindex) + alphaclone.slice(letterindex + 1);


      return ({alpha: alphaclone});


    });

    this.checkForLetter(letter, this.props.answer);
  }

  bonusRound(){

    if (this.state.bonus === false)
    {
      this.callLetter('R');

      this.callLetter('S');

      this.callLetter('T');

      this.callLetter('L');

      this.callLetter('N');

      this.callLetter('E');

      this.setState({bonus: true});
    }

  }

  render() {

    return (   
      <Grid>
        <Row className="show-grid" >
          {
            this.state.phrase.split(' ').map((item, j) =>
            (
                <div style = {{display:'inline-block'}}>
                <Letter letter = {' '}/>
                {item.split('').map((item, i) =>
                (                   
                  <Letter letter= {item}/>                   


                ))  }          
                </div>
            ))
          }

        </Row>
        <Row className="show-grid" style={{margin: '3vh'}}>
          {
            this.state.alpha.split('').map((item, i) =>
            (
                <Letter letter={item} key={i} onClick={this.callLetter}/> 
            ))
          }
        </Row>
        <Row className="show-grid" style={{margin: '3vh'}}>
          <ButtonToolbar>

            <CustomButton bsStyle = {"primary"} text= {"BONUS ROUND"} onClick = {this.bonusRound}/>
            <CustomButton bsStyle = {"danger"} text= {"REVEAL ALL"} onClick = {this.complete}/>
          </ButtonToolbar>
        </Row>
      </Grid>

    );
  }  
}

ReactDOM.render(
  <MyComponent answer='A VERY VERY EXCESSIVELY LONG TEST'/>,
  document.getElementsByClassName('container-fluid')[0]
);

Любая помощь очень ценится.

РЕДАКТИРОВАТЬ: Я не могу поверить, что я на самом деле должен явно заявить, что я не хочу копировать и вставлять его.

1 Ответ

0 голосов
/ 10 мая 2018

Для этого вам нужно сделать ручку, содержащую компонент в виде модуля. Вы можете сделать это, выбрав «Настройки»> «Javascript» и установив флажок «Добавить» type="module".

Затем вы можете импортировать компонент в другое перо, используя URL-адрес вашего пера:

import MyComponent from 'https://codepen.io/user/pen/xyz.js';

Полный документ по этому вопросу можно найти здесь: https://blog.codepen.io/2017/12/26/adding-typemodule-scripts-pens/. Надеюсь, это поможет:)

...