@Hahahahh

Метод класса в React?

const place = document.getElementById('news');
window.ee = new EventEmitter();

let my_news = [
  {
    title: 'Russia become the capital of our Galaxy Empire',
    text: 'Today is the most significant day in the history of mankind. Russia became the capital of the Intergalactic Empire. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi, rerum odit? Facere nobis numquam minima expedita, inventore dolore deserunt veritatis.',
    author: 'V.V.Pasdftin',
    like: 15200,
    dislike: 3400
  },
  {
    title: 'The level of agression of wild dogs increased',
    text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. A rem est soluta, error doloribus pariatur, vel autem ipsa sunt debitis voluptate commodi maiores atque earum. Asperiores excepturi magnam quibusdam vel. Similique minima nam facilis ea omnis distinctio ratione quae explicabo.',
    author: 'Citizen of 8s residence hall',
    like: 1230,
    dislike: 287
  },
  {
    title: 'The day when i become Hokage',
    text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet, at, fugiat ratione, consequuntur eum sed accusantium enim culpa iusto doloribus qui, odio id. Molestias eveniet officia eaque ut veritatis consequatur voluptates beatae ex, laborum, sunt modi laudantium odio error commodi.',
    author: 'Naruto Uzumaki',
    like: 2845,
    dislike: 3450
  },
  {
    title: 'How to make your RASENGAN bigger?',
    text: 'British scientists explore new way to expand your RASENGAN without registration and SMS. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos, omnis, assumenda. Itaque enim beatae officia nemo, harum id repudiandae ab deserunt ratione quaerat nihil culpa repellendus, placeat facilis quisquam exercitationem.',
    author: 'Some Anime character',
    like: 2454,
    dislike: 200
  }
];


class Title extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    data: React.PropTypes.shape({
    author: React.PropTypes.string.isRequired,
    title: React.PropTypes.string.isRequired,
    text: React.PropTypes.string.isRequired,
    like: React.PropTypes.number.isRequired,
    dislike: React.PropTypes.number.isRequired,
    likeState: true,
    dislikeState: true
    })
  };

  }


  render() {
    var data = this.props.data;
    var title = this.props.data.title,
        author = this.props.data.author,
        text = this.props.data.text,
        like = this.props.data.like,
        dislike = this.props.data.dislike;

    var newsTemplate = data.map(function(item, index) {
      return <div key = {index}>
        <div className="title_name"><p className = "title_textauthor">Title: {item.title}</p></div>
        <div className="title_text"><p>{item.text}</p></div>
        <div className="title_author"><p className = "title_textauthor">Author: {item.author}</p></div>
        <div className="title_rating">
        <p>Rating: <span className="likes"><i className="fa fa-thumbs-up" aria-hidden="true"></i>{item.like}</span>
        <span className="dislikes"><i className="fa fa-thumbs-down" aria-hidden="true"></i>{item.dislike}</span></p></div>
      </div>;
    })

    return <div className="title">{newsTemplate}</div>;
  }
}

class News extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      visible: false,
      titleChecked: true,
      textChecked: true,
      authorChecked: true,
      news: my_news
    };
    this.PostClick = this.PostClick.bind(this);
    this.ButtonClick = this.ButtonClick.bind(this);
  }

  PostClick() {

    var textEl = ReactDOM.findDOMNode(this.text);
    var titleEl = ReactDOM.findDOMNode(this.title);
    var author = ReactDOM.findDOMNode(this.author).value;
    var title = titleEl.value;
    var text = textEl.value;

    var item = [{
      title: title,
      author: author,
      text: text,
      like: 0,
      dislike: 0
    }];

    window.ee.emit('News.add', item);
    textEl.value = '';
    titleEl.value = '';
    this.setState({textChecked: true});
    this.setState({titleChecked: true});
  }

  FieldChange(fieldName, e) {
    if (e.target.value.trim().length > 0) {
      this.setState({[''+fieldName]:false})
    } else {
      this.setState({[''+fieldName]:true})
    }
  }

  componentDidMount() {
    var self = this;
    window.ee.addListener('News.add', function(item){
      var nextNews = item.concat(self.state.news);
      self.setState({news: nextNews})
    });
  }

  componentWillUnmount() {
    window.ee.removeListener('News.add');
  }

  ButtonClick() {
  this.setState({visible: !this.state.visible});
  }

  render () {
    var titleChecked = this.state.titleChecked,
        authorChecked = this.state.authorChecked,
        textChecked = this.state.textChecked;

    return <div>
            <div className= "makenewsbutton">
              <input
              style = {this.state.visible ? {display: 'none'} : {display: 'block'}}
              onClick = {this.ButtonClick} type= "submit" value = "Create news"/>
            </div>
            <form style = {this.state.visible ? {display: 'block'} : {display: 'none'}}>
            <div className = 'news_form'>
              <input type= 'text' className = "news_author" placeholder = "Author's name"
              ref = {(input) => this.author = input}
              onChange = {this.FieldChange.bind(this, 'authorChecked')}/>
              <input type= 'text' className = "news_title" placeholder = "Title's name"
              ref = {(input) => this.title = input}
              onChange = {this.FieldChange.bind(this, 'titleChecked')}/>
              <textarea cols="20" rows="10" placeholder = "News text"
              ref = {(input) => this.text = input}
              onChange = {this.FieldChange.bind(this, 'textChecked')}>
              </textarea>
            <div className = "news_form_buttons">
              <input type= "submit" value = "POST" onClick = {this.PostClick}
              disabled = {authorChecked || titleChecked || textChecked}/>
              <input onClick = {this.ButtonClick} type="submit" value = "CANCEL"/>
            </div>
            </div>
            </form>
            <Title data = {this.state.news}/>
          </div>;
  }
}

ReactDOM.render (
  <News />,
  place
);

При создании LikeCLick и DislikeClick возникает ошибка Uncaught TypeError: Cannot read property 'LikeClick' of undefined. И по всей видимости ошибка возникает просто при создании метода, не могу понять в чем дело. Заранее спасибо.
  • Вопрос задан
  • 368 просмотров
Пригласить эксперта
Ответы на вопрос 1
RomReed
@RomReed
JavaScript, Flutter, ReactNative, Redux, Firebase
https://jsfiddle.net/ggn96m21/
вы должны понимать что это примерный код и он возможно при копи-пасте работать не будет
но логика тут правильная.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы