有条件样式的事件定位

时间:2018-09-17 12:23:55

标签: reactjs ecmascript-6 react-props

因此,我试图使onClick函数在单击特定标签时使组件状态下的属性变为“ true”

这里是状​​态

constructor(props){
      super(props);
      this.state = {
        selected: false
      }
  }

这是一个函数,我只是将选择从false转换为true

  targetValue = (e) => {
      e.preventDefault();
      this.setState({selected: true});
  }




<div className="choose">
              <a href="#" onClick={this.targetValue} className={(this.state.selected ? "choosen" : "")}></a>
              <a href="#" onClick={this.targetValue} className={(this.state.selected ? "choosen" : "")}></a>
              <a href="#" onClick={this.targetValue} className={(this.state.selected ? "choosen" : "")}></a>
              <a href="#" onClick={this.targetValue} className={(this.state.selected ? "choosen" : "")}></a>
              <a href="#" onClick={this.targetValue} className={(this.state.selected ? "choosen" : "")}></a>
              <a href="#" onClick={this.targetValue} className={(this.state.selected ? "choosen" : "")}></a>
            </div>

这里的问题是,当我单击一个“ a”标签时,样式将应用于每个“ a”标签。我希望将其仅应用于单击的“ a”标签。我是否必须为每个“ a”标签制作一个单独的组件,或者是否有更合适的方法来应用此标签?

2 个答案:

答案 0 :(得分:2)

在此处检查:https://codesandbox.io/s/9l995oj90p

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      selected: 0
    };
  }
  targetValue = e => {
    e.preventDefault();
    const { id } = e.target;
    this.setState({ selected: id });
  };
  render() {
    console.log(this.state.selected);
    return (
      <div className="App">
        <a
          href="#"
          id={1}
          onClick={this.targetValue}
          className={this.state.selected === "1" ? "choosen" : ""}
        >
          Joj
        </a>
        <a
          href="#"
          id={2}
          onClick={this.targetValue}
          className={this.state.selected === "2" ? "choosen" : ""}
        >
          Joj
        </a>
        <a
          href="#"
          id={3}
          onClick={this.targetValue}
          className={this.state.selected === "3" ? "choosen" : ""}
        >
          Joj
        </a>
        <a
          href="#"
          id={4}
          onClick={this.targetValue}
          className={this.state.selected === "4" ? "choosen" : ""}
        >
          Joj
        </a>
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

答案 1 :(得分:0)

我假设您的问题是选择一个值,所以这就是我要做的:

  1. 创建一个值列表(每个值将与您的a标记相关联),并为每个值赋予一个ID(可以是一个非常简单的数字,例如0、1、2,... < / li>
  2. 修改targetValue,以便在单击a标记时,将selectedItem修改为刚刚单击的链接的ID。
  3. 如果choosen与ID相对应,则将selectedItem className添加到链接中