如何从组件中获取元素

时间:2015-09-02 12:16:58

标签: javascript reactjs

我有一些脚本,它需要元素,但我无法找到如何从react组件中获取它。至少,我可以在渲染后获得元素,但现在我有另一个问题 - 无法在按钮上制作事件,因为我需要SignatureObj

var SignaturePad = require('signature_pad');

var SignatureWidget = React.createClass({

    _handleClear: function(e, SignatureObj) {
        SignatureObj.clear();
    },

    _getSignature: function(canvas) {
        return new SignaturePad(canvas);
    },

    componentDidMount: function() {

        var wrapper = this.getDOMNode(),
            canvas  = wrapper.querySelector('canvas'),
            SignatureObj = this._getSignature(canvas);
    },

    render: function() {
        var canvas = React.createElement('canvas');

        return (
            <div>
                {canvas}
                <button>Clear</button>
            </div>
        );
    }
});

最后,我需要得到类似的东西

render: function() {
    var canvas = React.createElement('canvas'),
        >> canvasEl = canvas.getElement(),<< magic
        SignatureObj = this._getSignature(canvasEl);

    return (
        <div>
            {canvas}
            <button onClick={this._handleClear.bind(this, SignatureObj)}>Clear</button>
        </div>
    );
}

2 个答案:

答案 0 :(得分:0)

首先是一些注意事项,不推荐使用getDOMNode,你应该使用findDOMNode,进一步你不需要在渲染中使用create元素,因为如果你使用jsx语法你将它转换为语法你是使用(createlement ..etc ..引擎盖下)

关于选择元素的问题:

    React.findDOMNode(this.refs.findMe) 

&lt; - 让你找到节点或者你叫它:D(魔术)

    render: function() {
        return (
            <div>
                <canvas ref='findMe'></canvas> <------- magic
                <button>Clear</button>
            </div>
        );
    }

希望这有帮助! 一些好的读物:

参考文献: https://facebook.github.io/react/docs/more-about-refs.html

JSX: https://facebook.github.io/react/docs/jsx-in-depth.html

答案 1 :(得分:0)

我用这种方式添加事件

componentDidMount: function() {
    var pad             = this.refs.pad.getDOMNode(),
        saveButton      = this.refs.save.getDOMNode(),
        clearButton     = this.refs.clear.getDOMNode(),
        SignatureObj    = this._getSignature(pad);

    clearButton.onclick = this._handleClear.bind(this, SignatureObj);
    saveButton.onclick  = this._handleSave.bind(this, SignatureObj);
},