Как исправить элемент onClick. ReactJS - PullRequest
0 голосов
/ 21 марта 2020

Я новичок в ReactJS и у меня есть один вопрос. Я определил функцию showModal и но console.log() и this.setState({show:!this.state.show});.

И после этого я применил эту функцию onClick для элемента div внутри функции карты.

1-й вопрос: Когда я нажимаю на элементе div showModal работает, но в консоли я не вижу мой console.log.

2-й вопрос: я хочу сделать, когда вы нажимаете на один элемент div, он должен добавить / показать несколько новых элементов div, но только для одного элемента div (на который я нажал). Но теперь, когда я нажимаю на один элемент div, он добавляет / показывает новые элементы для всех элементов div, у которых была эта функция showModal.

Как я могу это исправить

import React, { Component } from "react";
import Modal from '../components/modal/form'

const DEFAULT_QUERY = 'redux';
const PATH_BASE = 'URL which work correct';


class Actions extends React.PureComponent{

    constructor(){
        super();
        this.state = {
            result:null,
            show:false,
            helpId:null
        };
        this.setSearchTopStories = this.setSearchTopStories.bind(this);
        this.showModal = this.showModal.bind(this);
        this.handleClickFromParent = this.handleClickFromParent.bind(this);
        this.onClose = this.onClose.bind(this);
    }
    onClose = e => {
        this.setState({ show: false});
    }

    handleClickFromParent = e => {
        this.setState({show: !this.state.show});
    }

    showModal = e => {
            console.log('BABE');
            this.setState({show: !this.state.show})
    };

    setSearchTopStories(result) {
        this.setState({ result });
    };
    componentDidMount() {        
        fetch(`${PATH_BASE}`)
            .then(response => response.json())
            .then(result => this.setSearchTopStories(result))

        .catch(error => error); 
    };

    render(){
        const { searchTerm, result } = this.state;
        console.log('* Actions Pure*');
        console.log(result);
        console.log('=');

        return(
        <div>
            {   
            (result !== null) ?
                result.map(
                (item,index) =>
                    <div>
                    <div onClick={()=>this.showModal()}>{item.name}</div>
                    <Modal 
                        id = {index}
                        handleClickFromParent {this.handleClickFromParent}
                        item = {[item]}
                        show = {this.state.show}
                        onClose = {this.onClose}>
                        YOLO
                    </Modal>
                    </div>
                )  
                : null 
            }

        </div>
        )
    }
}

export default Actions;

1 Ответ

0 голосов
/ 21 марта 2020

При выборе вы можете передать элемент по методу, а при нажатии вы можете установить значение элемента. Пожалуйста, проверьте код ниже.

Демо: https://codesandbox.io/s/stackoverflowmodal-19i36

this.state = {
          result: null,
          show: false,
          selectedItem:null,
          helpId: null
        };

//

showModal = (selectedItem) => {
        this.setState({
          show: !this.state.show,
          selectedItem
        });
      };

//

    class Actions extends React.PureComponent {
  constructor() {
    super();
    this.state = {
      result: null,
      show: false,
      selectedItem: null,
      helpId: null
    };
    this.setSearchTopStories = this.setSearchTopStories.bind(this);
    this.showModal = this.showModal.bind(this);
    this.handleClickFromParent = this.handleClickFromParent.bind(this);
    this.onClose = this.onClose.bind(this);
  }
  onClose = e => {
    this.setState({
      show: false
    });
  };

  handleClickFromParent = e => {
    this.setState({
      show: !this.state.show
    });
  };

  showModal = selectedItem => {
    this.setState({
      show: !this.state.show,
      selectedItem
    });
  };
  setSearchTopStories(result) {
    this.setState({ result });
  }
  componentDidMount() {
    fetch(`${PATH_BASE}`)
      .then(response => response.json())
      .then(result => this.setSearchTopStories(result))
      .catch(error => error);
  }
  render() {
    const { searchTerm, result, selectedItem } = this.state;
    return (
      <div>
        {result && result.length
          ? result.map((item, index) => (
              <div>
                <div onClick={() => this.showModal(item)}>{item.name}</div>
              </div>
            ))
          : null}
        {selectedItem && (
          <Modal
            id={index}
            handleClickFromParent={this.handleClickFromParent}
            item={[selectedItem]}
            show={this.state.show}
            onClose={this.onClose}
          >
            YOLO
          </Modal>
        )}
      </div>
    );
  }
}

export default Actions;
...