react-dom:在点击时逐渐改变元素的不透明度

react-dom: Incrementally change opacity of an element on click

我希望能够通过单击按钮增加 DOM 元素的不透明度

围绕 React 的概念,我认为这应该通过使用 state 和功能性 setState() 函数来完成。

但是,我使用以下代码使运行陷入错误:

import React, { Component } from 'react'

class ThoughtfulThoughts extends Component {

  state = {
    opacity: 0.4,
    thoughts:
      [
        "live and let leave",
        "just pee yourself",
        "who knows what 'laf' is?"
      ]
  }

  makeAppear = () => {
    // TODO: this causes a "RangeError: Maximum call stack size exceeded"
    this.setState(prevState => ({
      opacity: prevState.opacity + 0.2
    }))
  }

  render() {
    return (
      <div className="thoughtful-thoughts">
        <div className="current-thought" style={{opacity: this.state.opacity}}>
          {this.state.thoughts.map((thought, i) => (<p>{thought}</p>))}
        </div>
        <button onClick={this.makeAppear()}>Think for me</button>
      </div>
    )

  }
}

export default ThoughtfulThoughts

不想想要use jQuery, nor direct DOM manipulation,也不想 CSS transitions,但想在 "the React way".

中仅在 JS 中执行此操作

如有指点,将不胜感激!

您的代码中有几个小问题:

  1. 在您的按钮组件上,将 onClick={this.makeAppear()} 更改为 onClick={this.makeAppear}

  2. 在使用函数方法而不是对象方法基于先前的状态变量更新状态变量方面做得很好。但是,您有一个次要语法。要么:

    this.setState(prevState => (
      {opacity: prevState.opacity + 0.2}
    ));
    

    this.setState(prevState => {
      return {opacity: prevState.opacity + 0.2}
    });
    

    随你喜欢。

  3. map() 中为您 return 的每个项目添加 key 属性:所以基本上:

    {this.state.thoughts.map((thought, i) => (<p key={i}>{thought}</p>))}
    

    您可以在这里安全地使用 i 作为键,因为 thoughts 数组中的项目顺序将保持不变。有关密钥以及如何正确使用它们的更多信息,请查看 .


演示:

class ThoughtfulThoughts extends React.Component {
  constructor() {
    super();
    this.state = {
      opacity: 0.4,
      thoughts:
        [
          "live and let leave",
          "just pee yourself",
          "who knows what 'laf' is?"
        ]
    }
  }

  makeAppear = () => {
    this.setState(
      prevState => ({opacity: prevState.opacity + 0.2})
    );
  }

  render() {
    return (
      <div className="thoughtful-thoughts">
        <div className="current-thought" style={{opacity: this.state.opacity}}>
          {this.state.thoughts.map((thought, i) => <p key={i}>{thought}</p>)}
        </div>
        <button onClick={this.makeAppear}>Think for me</button>
      </div>
    );
  }
}

ReactDOM.render(<ThoughtfulThoughts />, document.getElementById("app"));
<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>
<div id="app"></div>