简体   繁体   中英

React.js: How to use the same button while passing variables to a click function

I am using material-ui as a UI framework and I am trying to create a view with two buttons that have different values.

  render: function() {

    return 
      <Card>
        <CardMedia overlay={<CardTitle title={this.props.title} />}>
          <img src={this.props.image}/>
        </CardMedia>
        <CardActions>
          <FlatButton onClick={this._handleClick} label="Good"/>
          <FlatButton onClick={this._handleClick} label="Bad"/>
        </CardActions>
      </Card>

Since I am new to react I think that I miss something basic. How can I pass values to FlatButton, can I use the "ref" attribute? My main problem is that I am using a framework. If I had written those components I would just use props, such as "label" and handle the click event from the component itself.

Update: found a solution, but still if feels like an anti-pattern...

      <FlatButton onClick={this._handleClick.bind(this, 1)} label="Good"/>
      <FlatButton onClick={this._handleClick.bind(this, 0)} label="Bad"/>

Appreciate the help...

You cannot call onClick on <button /> but you can pass a function to its onClick which is defined inside its Class . You will need to communicate your handleClick to its Child component through props

Hope you get it.

class CardActions extends React.Component {
 ...
}

class FlatButton extends React.Component {
    constructor(props) {
      super(props);
    }

    render() {
        return (
            <button onClick={() => this.props.whenClicked() } type="button">
                {this.props.label}
            </button>
        );
    }
}


class Cards extends React.Component {
    constructor(props) {
      super(props);
    }

    handleClick(event) {
        alert('click');
    }

    render: function () {

        return (
            <CardActions>
                <FlatButton whenClicked={(event) => this.handleClick(event)} title="Dropdown" />
            </CardActions >
        );
    }
};

I'd prefere to create two handling functions in the model:

handleGood: function() {},
handleBad: function() {},


<FlatButton onClick={this.handleGood} label="Good"/>
<FlatButton onClick={this.handleBad} label="Bad"/>

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