我希望您遇到我的同样问题。我有需要一个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添加事件?

最佳答案

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

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);
    });
}

关于javascript - 如何通过使用react在jquery中添加props函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53056990/

10-12 12:27
查看更多