React Map onClick和“ this”未定义

时间:2019-05-07 00:15:32

标签: reactjs this

已更新:

function TheCards() {
    let cardMasterList = require('./scryfall-oracle-cards.json')
    let cardMasterListSorted = sortByKey(cardMasterList, 'name')

    let [cardClicked, setCardClicked] = useState(null)

    //console.log(cardMasterList[0].name)
    //console.log(cardMasterListSorted)

    const handleClick = () => {
        setCardClicked('red')
        console.log(cardClicked)
        //Please make this do something with the clicked span tag!
    }

    return (
        <form id="card-master-list">
                {cardMasterListSorted
                    .filter(({legalities}) => legalities.vintage === 'legal')
                    .filter(({rarity}) => rarity === 'common' || 'uncommon')
                    .slice(0,10)
                    .map(
                    (cardName) => {
                        return (
                            <li key={cardName.id}>
                                <span className="card-name" onClick={ handleClick }>{cardName.name}</span>
                            </li>
                        )
                    }
                )
            }
        </form>
        )
}

更新:这是上面的更新代码。我仍然不知道如何引用我所单击的内容。我想做的不仅仅是改变文本的颜色,还要做一些简单的事情,就是使用“将其更改为红色”。我很伤心地说我缺少jQuery和其易“这个”参照点,因为像“this.handleClick”是行不通的。

function TheCards() {
    let cardMasterList = require('./scryfall-oracle-cards.json')
    let cardMasterListSorted = sortByKey(cardMasterList, 'name')

    console.log(cardMasterList[0].name);
    console.log(cardMasterListSorted)

    return (
        <form id="card-master-list">
                {cardMasterListSorted
                    .filter(({legalities}) => legalities.vintage === 'legal')
                    .filter(({rarity}) => rarity === 'common' || 'uncommon')
                    .map(
                    (cardName) => {
                        return (
                            <li key={cardName.id}>
                                <span className="card-name" onClick={ function DoTheThing() { document.querySelector('.card-name').style.color = 'red' } }>{cardName.name}</span>
                            </li>
                        )
                    }
                )
            }
        </form>
        )
}

我想要做的就是单击跨度时它变成红色。这似乎是不可能的,因为我没有尝试任何方法-编写另一个函数以我能想到的任何方式触发。 “这个”没有按预期工作。如何替换document.querySelector行使其起作用?

3 个答案:

答案 0 :(得分:0)

在使用React渲染时,不建议使用代码中的方法来更新UI。理想情况下,您将通过存储在组件状态下的样式数据来更新跨度样式:

<li key={cardName.id}>
    <span className="card-name" onClick={ 
        () => {
            /* Set the color state of component to red which triggers a
               render() and will update the style prop of the span 
               accordingly */
            this.setState({ color : 'red' });    
        }
    } style={{ color : this.state.color }}>
    {cardName.name}</span>
</li>

如果您真的想通过原始代码中的模式更新样式,则一种方法是通过"callback ref",它可以使您访问范围的相应DOM元素:

<li key={cardName.id}>
    <span className="card-name" ref={ (spanElement) => {

        spanElement.addEventListener('click', () => {

            spanElement.style.color = 'red';
        });
    }}>
    {cardName.name}</span>
</li>

答案 1 :(得分:0)

这是一个以React方式更新样式的示例:

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

const tiles = [
  {
    id: 1,
    n: "one"
  },
  { 
    id: 2, 
    n: "two" 
  }
];

const App = () => {
  const [clickedId, setClickedId] = useState(null);

  const click = id => {
    setClickedId(id);
  };

  return (
    <div style={{ display: "flex", flexDirection: "column" }}>
      {tiles.map(tile => (
        <div
          onClick={() => click(tile.id)}
          style={{ color: tile.id === clickedId ? "red" : "black" }}
        >
          {tile.n}
        </div>
      ))}
    </div>
  );
};

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

实时示例here

答案 2 :(得分:0)

那应该随你所愿。尽管正如codecubed.io所指出的那样,这并不是一种非常反应的方法。相反,最好切换一个类。像这样的东西:

const styles = {
  redTextClass: {
     color: 'red',
  }
}


<span className={stateVariable ? styles.redTextClass : null}></span>