Reactjs中组件上的事件处理程序

问题描述:

这不会触发组件,但是当我将我的事件处理程序附加到某个div时它就起作用。我是否需要在我的子组件中传递一个prop类型函数?Reactjs中组件上的事件处理程序

const buttonStyle = { 
    color: 'red' 
}; 

class Button extends React.Component { 
    render() { 
     return (
      <a className="social-button twitter"> 
      <i href="#" className="fa fa-twitter"></i> 
      </a> 
     )}; 
} 

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

    handleClick() { 
    console.log('this is:'); 
    } 

    render() { 
     return (
      <div> 
      <div onClick={(e) => this.handleClick(e)}> {/*this works attaching it to a div*/} 
      CLick me 
      </div> 
      <div className="social-buttons"> 
       <Button onClick={(e) => this.handleClick(e)} />{/*does now work attaching it to a component*/} 
      </div> 
      </div> 
     ) 
    } 
} 

ReactDOM.render(<PanelButtons />, document.querySelector('body')); 

做过什么,基本上是通过一个叫onClickButton组件回调。您可以通过组件的道具访问它。

class Button extends React.Component { 
    render() { 
     return (
      <a className="social-button twitter" onClick={this.props.onClick}> 
      <i href="#" className="fa fa-twitter"></i> 
      </a> 
     )}; 
} 

一旦Button组件的a元素被点击时,你通过了回调将被触发(和​​将被调用)。

上的<button />将按照您的预期工作。

但这是<Button />您创建一个组成部分,onClick将被作为道具,你可以通过onClick上的按钮组件的a标签下面调用一样,其handleClick将回调实际的onClick您PanelButtons组件。

const buttonStyle = { 
    color: 'red' 
}; 

class Button extends React.Component { 

    handleClick = (e) => { 
     this.props.onClick(e) 
    } 

    render() { 
     return (
      <a className="social-button twitter" onClick={this.handleClick}> 
      <i href="#" className="fa fa-twitter"></i> 
      </a> 
     )}; 
} 

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

    handleClick() { 
    console.log('this is:'); 
    } 

    render() { 
     return (
      <div> 
      <div onClick={(e) => this.handleClick(e)}> {/*this works attaching it to a div*/} 
      CLick me 
      </div> 
      <div className="social-buttons"> 
       <Button onClick={(e) => this.handleClick(e)} />{/*does now work attaching it to a component*/} 
      </div> 
      </div> 
     ) 
    } 
} 

ReactDOM.render(<PanelButtons />, document.querySelector('body')); 

如果你只是想添加在PanelButtons每个按钮的onClick,只需修改通过在div标签添加事件监听呈现这样一点点。

render() { 
    return (
     <div> 
     <div onClick={(e) => this.handleClick(e)}> {/*this works attaching it to a div*/} 
     CLick me 
     </div> 
     <div className="social-buttons" onClick={(e) => this.handleClick(e)}> 
      <Button />{/*does now work attaching it to a component*/} 
     </div> 
     </div> 
    ) 
} 

你应该道具向下传递到<Button />组件

class Button extends React.Component { 
    render() { 
     return (
      <a className="social-button twitter" {...this.props}> 
      <i href="#" className="fa fa-twitter"></i> 
      </a> 
     )}; 
} 

更多阅读:JSX spread attributes