如何显示突出显示的单词的下拉菜单

时间:2019-09-11 07:25:30

标签: javascript reactjs api

因此在我的代码中,单词被突出显示。在突出显示的单词中,我想显示一个下拉菜单,该菜单将执行诸如更改文本颜色的操作。我还想知道如何为每个突出显示的单词显示动态单词。这些动态词将从api接收。无论如何,即使是静态单词列表也没有显示在下拉菜单中。

代码的沙箱: https://codesandbox.io/s/affectionate-meninsky-tdqru

反应码

import React, { Component } from "react";

import "./App.css";

const stripChars = word => word.replace(/[\W_]+/g, "");

class App extends Component {
  state = {
    text: "The gun is a dangerous weapon, don't kill anyone",
    highlight: ["gun", "kill"]
    // text: "",
    // highlight: []
  };

  componentDidMount() {
    fetch("https://api.myjson.com/bins/1ep1fh")
      .then(res => res.json())
      .then(result => {
        console.log(result);
        let text = "";
        let highlight = [];
        for (const item of result) {
          text += item.text + "\n";
          highlight = [...highlight, ...item.highlight];
        }
        this.setState({
          text,
          highlight
        });
      });
  }

  render() {
    const { text, highlight } = this.state;
    const words = text.split(" ");
    return (
      <div>
        {words.map((word, i) => (
          <span key={i}>
            <span
              id="new"
              className={
                highlight.includes(stripChars(word)) && "highlight dropbtn"
              }
              onClick="myFunction()"
            >
              {word}
            </span>
            &nbsp;
          </span>
        ))}
        <div id="myDropdown" class="dropdown-content">
          <a href="#was">was</a>
          <a href="#were">were</a>
          <a href="#will">will</a>
        </div>
      </div>
    );
  }
}

export default App;

javascript文件

function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

window.onclick = function(event) {
  if (!event.target.matches(".dropbtn")) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains("show")) {
        openDropdown.classList.remove("show");
      }
    }
  }
  if (event.target.tagName === "A") {
    var color;
    var _href = event.target.getAttribute("href");
    switch (_href) {
      case "#was":
        color = "green";
        break;
      case "#were":
        color = "Aqua";
        break;
      case "#will":
        color = "Magenta";
        break;
      default:
        color = "red";
    }
    document.getElementById("new").style.color = color;
  }
};

css文件

.App {
  text-align: center;
}
.highlight {
  background: red;
  text-decoration: underline;
}

.dropbtn {
  color: white;

  font-size: 16px;
  border: none;
  cursor: pointer;
}

.dropbtn:hover,
.dropbtn:focus {
  background-color: #2980b9;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {
  background-color: #ddd;
}

.show {
  display: block;
}

1 个答案:

答案 0 :(得分:0)

您不应引用外部函数,而应通过DOM操作来实现此目的。您可以只创建一个状态变量,然后根据点击的单词进行切换。下拉显示可以绑定到相同的变量。

sheet.getRange(range.getRow(), 1, 1, sheet.getLastColumn()).copyTo(targetRange, SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);

// css:无需添加显示:无

import React, { Component } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const stripChars = word => word.replace(/[\W_]+/g, "");

class App extends Component {
  state = {
    text: "The gun is a dangerous weapon, don't kill anyone",
    highlight: ["gun", "kill"],
    displayDrop: false
    // text: "",
    // highlight: []
  };

  componentDidMount() {
    fetch("https://api.myjson.com/bins/1ep1fh")
      .then(res => res.json())
      .then(result => {
        console.log(result);
        let text = "";
        let highlight = [];
        for (const item of result) {
          text += item.text + "\n";
          highlight = [...highlight, ...item.highlight];
        }
        this.setState({
          text,
          highlight
        });
      });
  }

  render() {
    const { text, highlight } = this.state;
    const words = text.split(" ");
    return (
      <div>
        {words.map((word, i) => (
          <span key={i}>
            <span
              id="new"
              className={
                highlight.includes(stripChars(word)) && "highlight dropbtn"
              }
              onClick={() => this.setState({ displayDrop: true })}
            >
              {word}
            </span>
            &nbsp;
          </span>
        ))}
        {this.state.displayDrop && (
          <div id="myDropdown" class="dropdown-content">
            <a href="#was">was</a>
            <a href="#were">were</a>
            <a href="#will">will</a>
          </div>
        )}
      </div>
    );
  }
}

export default App;

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

以上代码将处理下拉菜单的显示。您也可以将选项保存为状态,并根据单击元素的方式更改选项。