是否可以扩展JSX / React以允许自定义指令?

时间:2019-03-29 15:11:46

标签: reactjs jsx directive

例如,我是否可以定义一个trackClick={}之类的属性,以便可以像这样在我的JSX代码中使用它?

class MyComponent extends React.Component {

  render() {
    return <a href="/foo" trackClick={{ some: "data" }}>bar</a>
  }

}

export default withTracking(MyComponent)

function withTracking(WrappedComponent) {
  // do something here to make `trackClick` possible?
}

1 个答案:

答案 0 :(得分:0)

react HOC是您需要了解的内容:

function withTracking(WrappedComponent) {
  return class extends React.Component {
    // this.props.trackClick
    trackHandler => (trackClick) => (e) => {
       // prevent default, since you're using `a` tag
       e.preventDefault()
      // do something with trackClick
    }
    render() {
      const { trackClick, ...rest } = this.props
      return <WrappedComponent 
        onClick={this.trackHandler(trackClick)} 
        {...rest}
      />;
    }
  }
}