Добавить событие в компонент без состояния в ReactJS - PullRequest
0 голосов
/ 29 июня 2018

Есть ли какой-нибудь способ прикрепить Event к Component без состояния? Позвольте мне объяснить мой вопрос ниже:

У меня есть компонент без сохранения состояния для кнопки bootstrap:

export const Button = props => {
  return (
    <button
      className={`btn btn-${props.type} ${props.class}`}
      type={props.buttonType}
    >
      {props.children}
    </button>
  );
};

И я использую компонент <Button/> в Parent Компонент под названием Container как:

class Container extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  sendData() {
    // method logic
  }

  render() {
    return (
      <Button type="primary" class="">
        Save Changes
      </Button>
    );
  }
}

Чтобы вызвать sendData() метод, нажав на компонент Button, который я пробовал:

<Button type="primary" onClick={() => this.sendDate()}>
  Save Changes
</Button>

Но это не работает.

Есть ли какой-либо возможный способ прикрепить событие к Component без состояния, чтобы вызвать Method из Parent Component.

Я ищу в Google, но не смог найти решение этого вопроса, поэтому, пожалуйста, помогите мне, если у вас есть какое-либо решение. Большое спасибо:)

Ответы [ 3 ]

0 голосов
/ 29 июня 2018
export const Button = (props) => {
return(
    <button 
        className={`btn btn-${props.type} ${props.class}`} 
        type={props.buttonType}
        onClick={props.onClick}
        >
        {props.children}
    </button>
  )
}
0 голосов
/ 29 июня 2018

Я думаю, что вы имели в виду, чтобы вызвать функцию из родительского компонента из дочернего компонента?

Итак:

export const Button = (props) => {
  const buttonOnClick = this.props.buttonOnClick;

  return (
    <button 
      className={`btn btn-${props.type} ${props.class}`} 
      type={props.buttonType}
      {props.children}
      onClick={buttonOnClick(e)} // Onclick handled here calling the parent function via props.
    >
    </button>
  )
}



class Container extends Component {
    constructor(props) {
        super(props);
        this.state = { }
    }

    sendData(event) {
        // method logic
    }

    render() { 
        return ( <Button type='primary' class='' buttonOnClick={(e) => this.sendData(e)}>Save Changes</Button> )
    }
}

По сути, функция sendData передается от родительской функции к дочернему элементу в качестве реквизита и вызывается через onClick.

0 голосов
/ 29 июня 2018

Вам нужно будет передать обработчик событий вашему Button компоненту и добавить onClick к html button компоненту по умолчанию

Попробуйте следующее:

export const Button = (props) => {
    return(
        <button 
            onClick={props.onClick}
            className={`btn btn-${props.type} ${props.class}`} 
            type={props.buttonType}>
            {props.children}
        </button>
    )
}

class Container extends Component {
    constructor(props) {
        super(props);
        this.state = {  }
    }

    sendData(e) {
        // logic here
    }

    render() { 
        return ( <Button onClick={(e) => this.sendData(e) } type='primary' class=''>Save Changes</Button> )
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...