繁体   English   中英

如何从.jsx脚本调用ReactJS元素上的jQuery函数?

[英]How do you call a jQuery function on a ReactJS element from .jsx script?

我刚刚开始学习ReactJS,这件事发生在我身上。

例如:

我想对reactjs元素执行的函数:

function initializeInput(selector, color) {
    // just an example function
    $(selector).css("font-size", "21pt");
}

和我的.jsx文件的一部分:

var myInput = React.createClass({
componentDidMount: function () {
    initializeInput("#" + this.props.inputId);
},
render: function() {
    return (
        <input type="text" value="text goes here" 
               name={this.props.inputName} 
               id={this.props.inputId}/>
    );
}
});

这个函数被成功调用,但没有任何反应,似乎事情不仅仅是用jQuery和React这样做。 将它们混合起来甚至是好的吗? 谢谢。

Jquery与Reactjs非常合作。 您可以在反应渲染之后调用jquery函数,即在componentDidMount和中

你可以为此做出反应。 让我们说你想要一个工具提示

var myInput = React.createClass({
componentDidMount: function () {
    $(this.refs.tooltip).tooltip();
},
render: function() {
    return (
        <input ref="tooltip" type="text" value="text goes here" 
               name={this.props.inputName} 
               id={this.props.inputId}/>
    );
}
});

首先,您需要渲染组件元素( render函数),然后在componentDidMount处理程序中调用您的jquery代码

http://jsbin.com/zupagav/1/edit?js,console,output

我相信使用this.refs就是这样。 我认为你不应该需要React.findDomNode 更多关于React文档的引用。

var myInput = React.createClass({
  componentDidMount: function () {
    initializeInput(this.refs.inputId);
  },

  render: function() {
    return (
      <input 
        ref="myInput"
        type="text" 
        value="text goes here" 
        name={this.props.inputName} 
        id={this.props.inputId} />
    );
  }
});

这对于第三方库(如jQuery,d3,做画布等)非常有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM