React:从点击链接获取属性

时间:2018-04-17 15:33:04

标签: javascript reactjs

我有一个反应标记,它接受一个url prop并将输出转换为一个链接。单击该链接后,我创建一个引导模式,询问用户是否要继续。我有一个for循环为不同的链接创建多个标签,它会显示与网址的链接。单击任何URL也会打开包含一些信息的模态框,但我的模态上的继续按钮始终链接到第一个元素。以下是展示其实际效果的视频:enter image description here

这里是ExternalUrl标记的代码:

import React, { Component, Fragment } from 'react';
import {tu} from "../../utils/i18n";

class ExternalUrl extends Component {
render() {
 return (
  <div>
    <a href="#" data-toggle="modal" data-target="#ExternalUrlWarning">{this.props.url}</a>

    <div class="modal fade" id="ExternalUrlWarning" tabindex="-1" role="dialog" aria-labelledby="ExternalUrlWarning" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="ExternalUrlWarningLabel">External Link</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            {tu("The link")} <b> {this.props.url} </b> {tu("is not a verified site and therefore may not be secure. Proceed at your own risk.")} 
          </div>
          <div class="modal-footer">
            <a class="btn btn-warning" href={this.props.url} target="_blank">{tu("Proceed")}</a>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">{tu("Cancel")}</button>
          </div>
        </div>
      </div>
    </div>
  </div>
  );
 }
}

export default ExternalUrl;

以下是使用ExternalUrl标记的代码:

witnesses.map((account, index) => (
            <tr key={account.address}>
              <td><ExternalUrl url={account.url}></ExternalUrl></td>
            </tr>
          ))

2 个答案:

答案 0 :(得分:0)

为您的元素创建一个on click处理程序并传递URL

witnesses.map((account, index) => (
  <tr key={account.address} onClick={() => this.handleClick(account.url)}>
    <td><ExternalUrl url={account.url}></ExternalUrl></td>
  </tr>
))

...

handleClick(url) {
    console.log('url', url)
    // handle your modal state here
}

答案 1 :(得分:0)

您在id="ExternalUrlWarning"组件中使用ExternalUrl

您正在循环验证并生成多个ExternalUrl组件。但是对于所有模态,id都是相同的(ExternalUrlWarning)。

将索引传递给ExternalUrl组件,如下所示

witnesses.map((account, index) => (
        <tr key={account.address}>
          <td><ExternalUrl url={account.url} index={index}></ExternalUrl></td>
        </tr>
      ))

并使用它来构造模态的id。

<a href="#" data-toggle="modal" data-target={"#ExternalUrlWarning_"+this.props.index}>{this.props.url}</a>

<div class="modal fade" id={"ExternalUrlWarning_"+this.props.index} tabindex="-1" role="dialog" aria-labelledby="ExternalUrlWarning" aria-hidden="true">