有没有办法定义类似于角度的自定义属性?

时间:2018-02-03 07:25:55

标签: javascript reactjs ecmascript-6

考虑用例。我希望在我的反应应用程序中有一个工具提示功能。我想要设置它的方式是当我写<input type="text" tooltip="Enter your name here">时,这应该应用工具提示,说明&#34;在文本框中输入您的姓名&#34; 。这应该适用于我的应用中的任何符合条件的元素。因此,每当我需要在任何元素上应用工具提示时,我只需要在其上写tooltip="..."属性。

我很熟悉在AngularJS中你可能会这样做。

angular.module('app')
.directive('tooltip', function() {
  return {
    restrict: 'A',
    link: function($scope, $el) {
       // Apply Tooltip through JS or applying right CSS class
    }
  }
}

但我不确定React中是否有类似的东西。或者如果需要构建,我应该如何创建这样的东西。

2 个答案:

答案 0 :(得分:1)

The question is basically whether React has the concept of directives. And the answer is no.

React offers components that are supposed to be composed. As opposed to Angular components, React components don't necessarily create DOM elements, so nested components won't put restrictions on the layout.

So tooltip should be defined as a component:

class Tooltip extends React.Component {
  render() {
    const child = React.Children.only(this.props.children);

    return React.cloneElement(
      child,
      { className: classNames(child.props.className, 'tooltip') }
    );
  }

  componentDidMount() {
    const childElement = ReactDOM.findDOMNode(this).children[0];
    const tooltipText = this.props.title;
    // init a tooltip
  }

  componentWillUnmount() {
    // clean up a tooltip
  }
}

And used like:

<Tooltip title="foo"><Foo/></Tooltip>

答案 1 :(得分:0)

This it could be something like that.. though I wouldn't recommend fiddling with DOM really.

class TooltipProvider extends React.Component {
  componentDidMount() {
    document.querySelectorAll('[tooltip]').forEach(el => {
       // set up a tooltip
    });
  }

  componentDidUpdate() {
    document.querySelectorAll('[tooltip]').forEach(el => {
       // set up a tooltip
    });
  }


  render() {
    return children;
  }

}

// somwhere in your app

return () {
   <TooltipProvider>
      // The rest of the app
   </TooltipProvider>
}