简体   繁体   中英

How to run React function within another component

I have two components. They both render fine. Component one is inside component two. A button inside a box.

When I click the button I want to alert('hello'), but no success... However, if I insert the button-component alone in class Main it works...

Component one:

class Button extends Component {
  sayHello() {
    alert("hello!");
  }

  render() {
    return (
      <div>
        <button onClick={() => this.sayHello()}>PRESS</button>
      </div>
    );
  }
}

export default Button;

Component two:

class Box extends Component {
  render() {
    return (
      <div>
        <h1>I just want say...</h1>
        <Button />
      </div>
    );
  }
}

export default Box;

index.js :

class Main extends React.Component {
  render() {
    return (
      <div>
        <Box />
      </div>
    );
  }
}

ReactDOM.render(<Main />, document.getElementById("root"));

My CSS styling changed the z-index making the button unclickable. Changed position absolute to relative, works fine now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM