在React中单击Component时,将类添加到兄弟节点

时间:2017-04-16 17:40:57

标签: javascript html css reactjs components

我正在使用React.js构建我的投资组合。在一个部分中,我有四个组件布局在网格中。我想要实现的是,当单击一个组件时,会将css类添加到此组件的兄弟节点,以便减少其不透明度并仅保留单击的组件。在jQuery中,它会像$(' .component')on(' click',function(){$(this).siblings.addClass(' fadeAway& #39;)})。我怎样才能达到这个效果?这是我的代码,提前感谢任何和所有的帮助!

class Parent extends Component{
  constructor(){
    super();
    this.state = {fadeAway: false}
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick(){
    //Add class to siblings
  }
  render(){
    const array = ["Hello", "Hi", "How's it going", "Good Times"]
    return(
      array.map(function(obj, index){
        <Child text={obj} key={index} onClick={() => this.handleClick} />
      })
    )
  }
}

4 个答案:

答案 0 :(得分:1)

这个问题的一个工作示例可能看起来像这样,初始化数组稍微复杂一些:

class Parent extends Component{
  constructor(){
    super();
    this.state = {
      elements: [
        {
          id: "hello",
          text: "Hello",
          reduced: false,
        },

        {
          id: "hi",
          text: "Hi",
          reduced: false,
        }

        {
          id: "howsItGoing"
          text: "How's it going",
          reduced: false,
        }

        {
          id: "goodTimes",
          text: "Good Times",
          reduced: false,
        }
      ],
    }

    this.handleClick = this.handleClick.bind(this)
  }

  handleClick(e){
    // copy elements from state
    const elements = JSON.parse(JSON.stringify(elements));
    const newElements = elements.map(element => {
      if (element.id === e.target.id) {
        element.reduced = false;
      } else {
        element.reduced = true;
      }
    });


    this.setState({
      elements: newElements,
    });
  }

  render(){
    return(
      this.state.elements.map(function(obj, index){
        <Child
          id={obj.id}
          text={obj.text}
          reduced={obj.reduced}
          key={index}
          onClick={() => this.handleClick} />
      });
    );
  }
}

然后你只需要添加一个这样的三元组Child组件:

<Child
  id={this.props.id}
  className={this.props.reduced ? "reduced" : ""} />

这比其他示例增加了一些样板,但是将业务逻辑与组件内的文本联系起来非常脆弱,而更强大的解决方案需要更强大的标识,如呈现的DOM元素上的ID或类。如果您愿意,此解决方案也可以轻松地扩展您的逻辑,以便多个元素可以同时保持最大不透明度。

答案 1 :(得分:1)

我只是存储在所选项的状态索引中,然后将fadeAway prop传递给定义为

的子组件
fadeAway={this.state.selectedIndex !== index}

之后,您只需要根据fade-away在Child中设置this.prop.fadeAway类,并定义必要的CSS规则。

以下是您的案例:

class Parent extends React.Component{
  constructor () {
    super();
    this.state = {selectedIndex: null}
  }
  handleClick (selectedIndex) {
    this.setState({ selectedIndex })
  }
  render () {
    const array = ["Hello", "Hi", "How's it going", "Good Times"]
    return (
      <div>
        {array.map((obj, index) => {
          const faded = this.state.selectedIndex && this.state.selectedIndex !== index
          return <Child 
            text={obj} 
            fadeAway={faded}
            key={index} 
            onClick={() => this.handleClick(index)} />
        })}
      </div>  
    )
  }
}

class Child extends React.Component {
  render () {
    return (
      <h2
        onClick={this.props.onClick}
        className={this.props.fadeAway ? 'fade-away' : ''}>
        {this.props.text}
      </h2>  
    ) 
  }
}

ReactDOM.render(
  <Parent />,
  document.body
);
.fade-away {
  opacity: 0.3;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

答案 2 :(得分:0)

您可以使用切换变量来实现:

current page's

答案 3 :(得分:0)

我使用像currentWord这样的状态来保存在父组件中单击的单词,presudo代码如下所示:

class Parent extends Component {
  constructor(){
    super();
    this.state = {
      fadeAway: false,
      currentWord: ''
    };
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick(currentWord){
    this.setState({
      currentWord: currentWord,
    });
  }
  render(){
    const array = ["Hello", "Hi", "How's it going", "Good Times"]
    const currentWord = this.state.currentWord;
    return(
      array.map(function(obj, index){
        <Child currentWord={currentWord} text={obj} key={index} onClick={() => this.handleClick} />
      })
    )
  }
}

在子组件中

class Child extends Component {
  // some other code

  handleClick(e) {
    this.props.handleClick(e.target.value);
  }

  render() {
    const isSelected = this.props.text === this.props.currentWord;
    // use isSelected to toggle className

    <div
      onClick={this.handleClick.bind(this)}
    >{this.props.text}
    </div>
  }
}