获取渲染层 Onclick React

Get Rendered Layer Onclick React

var Component = React.createClass({
    onClickButton : function(){
        //i want layer in this function
    },
    render: function () {
         return (
            <div className="Component">
                  <button onClick={this.onClickButton}>Click Me</button>
            </div>
         ); 
    }
});

function renderNow(data,layer){
    ReactDOM.render(
        <Component data={data} />,
        layer
        );
}

使用 renderNow({name: 'John' },someLayer);

调用

我希望 layer 位于 onClickButton 函数中,该函数通过 renderNow 函数传递。

我尝试将层传递给 render 函数和 setState layer 但它给了我 Whosebug 错误

我不确定层到底是什么以及你想要实现什么,但我想你应该能够将层作为道具传递给你的组件。

function renderNow(data,layer){
    ReactDOM.render(
        <Component data={data} layer={layer} />,
        layer
    );
}

然后

...
onClickButton : function(){
    this.props.layer //i want layer in this function
},
...

马立克的 is the way I would do it...but there's another way using ReactDOM.findDOMNode()

var Component = React.createClass({
    onClickButton : function() {
        //i want layer in this function
        const layer = ReactDOM.findDOMNode(this); // <-- Here you go
    },
    render: function () {
         return (
            <div className="Component">
                  <button onClick={this.onClickButton}>Click Me</button>
            </div>
         ); 
    }
});

参考: https://facebook.github.io/react/docs/react-dom.html


通知:

文档通常建议不要突破组件抽象:

Note:

findDOMNode is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction.