簡體   English   中英

在ReactJS中向無狀態組件添加事件

[英]Add an event to a Stateless Component in ReactJS

有沒有可能的方法將Event附加到無狀態Component 我來解釋一下我的問題:

我有一個無狀態組件用於bootstrap按鈕:

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

我在Parent Component中使用名為Container<Button/>組件:

class Container extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  sendData() {
    // method logic
  }

  render() {
    return (
      <Button type="primary" class="">
        Save Changes
      </Button>
    );
  }
}

要通過單擊Button組件調用sendData()方法,我嘗試過:

<Button type="primary" onClick={() => this.sendDate()}>
  Save Changes
</Button>

但這不起作用。

是否有任何可能的方法將事件附加到無狀態Component以從Parent組件調用Method

我在Google上搜索但無法找到此問題的解決方案,所以如果您有任何解決方案,請幫助我。 非常感謝 :)

您需要將事件處理程序傳遞給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> )
    }
}

我認為你的意思是從子組件的父組件調用一個函數?

所以:

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函數作為props從父函數傳遞給子函數,並通過onClick調用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM