如何通过使用react在jquery中添加props函数

时间:2018-10-30 03:32:31

标签: javascript jquery reactjs

我希望您遇到我的同样问题。我有需要一个jquery事件,如(单击,更改)的反应代码。这是我的代码。

export default class SamplePreviewComponent extends React.Component <Props, any> {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.renderChoiceButton();
    }

    renderChoiceButton() {
        $('input.st').on('click', function(){
           let value = $(this).val();
           this.props.addDependentSample(value);
        });
    }

    render() {
        const {sampleTree} = this.props;
        return (
                <div className='row pl-1 pr-1 pt-0 mb-1'>
                    <div className='columns bg-black20 pt-1 pb-1 border-radius-sm'>
                        <div  className='mb-1'>
                            <p className='subheader'><strong><small>SAMPLE #1</small></strong></p>
                            {sampleTree.root.label.trim().length > 0 && <h4>{sampleTree.root.label}</h4>}
                            {sampleTree.root.subLabel && sampleTree.root.subLabel.trim().length > 0 &&  <span className='subheader'><small><strong>{sampleTree.root.subLabel}</strong></small></span>}
                        </div>
                        <div>                             
                            <div dangerouslySetInnerHTML={{ __html: sampleTree.root.generatedHtml }} className="red"/>
                        </div>
                    </div>
                </div>
        );
    }
}

如果您检查我组件的返回值。添加了dangerouslySetInnerHTML。输出是这样的

 <div>
    <div class="fancy-checkbox fancy-hover small mb-0">
        <input type="checkbox" class="st" id="_0" name="17[]" value="1">
        <label for="_0">1</label>
    </div>
    <div class="fancy-checkbox fancy-hover small mb-0">
        <input type="checkbox" class="qt" id="_1" name="17[]" value="2">
        <label for="_1">2</label>
    </div>
</div>

当用户单击复选框时。我将使用jQuery添加和事件

 renderChoiceButton() {
        $('input.st').on('click', function(){
           let value = $(this).val();
           this.props.addDependentSample(value);
        });
    }

我收到一个错误Cannot read property 'addDependentSample' of undefined。也许是因为它来自react道具,而jquery无法读取它。如何使用jquery添加事件以将函数连接起来进行反应?

1 个答案:

答案 0 :(得分:2)

有几种方法可以解决此错误-一种简单的方法是存储对组件实例的引用(即componentInstance,如下所示),然后通过该实例访问组件的prop,例如所以:

renderChoiceButton() {

    // Store reference to component for access in click handler
    const componentInstance = this;

    $('input.st').on('click', function() {

       let value = $(this).val();
       // Access props for the component via componentInstance
       componentInstance.props.addDependentSample(value);
    });
}