向ReactJS中的无状态组件添加事件

时间:2018-06-29 07:35:59

标签: javascript reactjs event-handling

有没有可能将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的方法。

我在Google上进行了搜索,但无法找到此问题的解决方案,因此,如果您有任何解决方案,请帮助我。非常感谢:)

3 个答案:

答案 0 :(得分:2)

您将需要将事件处理程序传递到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> )
    }
}

答案 1 :(得分:2)

我认为您的意思是从子组件的父组件调用函数?

所以:

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调用。

答案 2 :(得分:1)

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