React — onClick handler in Btn component AND parent

reactjs onclick

834 просмотра

3 ответа

1053 Репутация автора

I have a Btn component with some style toggles in an onClick inside that component.

I want to add an onClick to the parent to carry out a function when the button is clicked. The btn component will be reused so the onClick in the parent component will change, while the onClick in the Btn component will always only just toggle btn styles.

FIDDLE

class BtnParent extends React.Component {
 constructor(props) {
    super(props);
    this.alsoDoThis = this.alsoDoThis.bind(this);
  }
  alsoDoThis() {
    alert('clicked');
  }
  render() {
    return (
      <BtnFav onClick={this.alsoDoThis} />
    );
  }
};
Автор: Kirk Ross Источник Размещён: 18.07.2016 10:37

Ответы (3)


0 плюса

2538 Репутация автора

You pass the onClick prop to the child but you never use it.The function needs to be invoked explicitly:

 handleClick() {
    this.props.onClick(); // invoke it anywhere in the child
    this.setState({favorited: !this.state.favorited});
 }
Автор: Igorsvee Размещён: 18.07.2016 11:07

0 плюса

31 Репутация автора

btnParent.jsx below:

class BtnParent extends React.Component {
 constructor(props) {
    super(props);
    this.alsoDoThis = this.alsoDoThis.bind(this);
  }
  alsoDoThis() {
    alert('clicked');
  }
  render() {
    return (
      <BtnFav alsoDoThis={this.alsoDoThis} />
    );
  }
};

btnFav.jsx below:

class BtnFav extends React.Component {
  render() {
    return (
      <button onClick={this.props.alsoDoThis} />
    );
  }
};

can solve it!


Component communication between parent and child, you can use react props to pass the function, but when two components are not parent / child, you can use some event publish / subscribe lib. such as https://github.com/hustcc/onfire.js

Автор: atool Размещён: 19.07.2016 05:49

0 плюса

562 Репутация автора

Try this out,

   class BtnFav extends React.Component {
      render() {
        return (
          <button onClick={()=>this.props.alsoDoThis()} />
        );
      }
    };
Автор: Vaibhav Singh Размещён: 01.05.2017 08:26
Вопросы из категории :
32x32