简体   繁体   English

React.js:如何在将变量传递给click函数时使用相同的按钮

[英]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. 我正在使用material-ui作为UI框架,并且尝试使用具有不同值的两个按钮创建视图。

  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? 如何将值传递给FlatButton,是否可以使用“ ref”属性? 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. 如果我已经编写了这些组件,那么我将只使用道具(例如“ label”)并处理来自组件本身的click事件。

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 . 您不能在<button />上调用onClick,但可以将函数传递给在Class定义的onClick。 You will need to communicate your handleClick to its Child component through props 您将需要通过propshandleClick与其子组件进行通信

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"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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