【问题标题】:How can I manipulate HTML elements with React and style them如何使用 React 操作 HTML 元素并设置它们的样式
【发布时间】:2020-06-05 21:28:37
【问题描述】:

我目前正在尝试以下操作。

class MyComponent extends React.Component {
    changeColor() {
        document.getElementbyId("test").style.color = "green";
    }
    render() {
        return (
            <button id={MainStyles.test} onClick={this.changeColor} >
                Hello World
            </button>
        );
    }
}

export { MyComponent };

现在这适用于 window.alert("hello world") 等事件,但不适用于上面的代码,并最终产生此错误

“TypeError:无法读取 null 的属性 'style'”

我相信这是由于 document.getElementbyId,ref 会解决这个问题吗?如果是这样,我会怎么做?

【问题讨论】:

    标签: javascript reactjs event-handling jsx gatsby


    【解决方案1】:

    Mainstyles.test 可能不会生成字符串“test”。不看更多代码是不可能知道的。此外,还有一种更简单的方法来引用 .对于传递给 onClick 属性的每个函数,都有一个事件。这个事件是一个对象,你可以这样重构:

    class MyComponent extends React.Component {
        changeColor(event) {
            event.target.style.color = "green";
        }
        render() {
            return (
                <button onClick={event => this.changeColor(event)} >
                    Hello World
                </button>
            );
        }
    }
    
    export { MyComponent };
    

    【讨论】:

      【解决方案2】:

      React 中有多种方法可以操作和设置 HTML 元素的样式(通常不使用 getElementbyIdquerySelector 或任何其他 Document 方法。)

      正如 Kasper 在他的回答中提到的那样

      每个传入 onClick 属性的函数都有一个事件。

      所以你可以很容易地从点击事件中获取目标来访问 HTML 元素。

      import React from "react"
      
      const MyComponent = () => {
        const changeColor = e => {
          e.target.style.color = "green"
        }
        return <button onClick={changeColor}>Hello World</button>
      }
      
      export { MyComponent }
      

      也许您不想操作按钮本身,而是要操作另一个 HTML 元素。 Refs 可能是实现此目的的一种方式,但 the React docs suggest to avoid this if you can do it declaratively.

      import React, { useRef } from "react"
      
      const MyComponent = () => {
        const myRef = useRef()
      
        const handleClick = () => {
          myRef.current.style.color = "green"
        }
      
        return (
          <div>
            <button onClick={handleClick}>Hello World</button>
            <p ref={myRef}>Hello world!</p>
          </div>
        )
      }
      
      export { MyComponent }
      

      在某个阶段,您的组件将达到需要使用状态来跟踪事物的程度。

      在这种情况下,我们倾向于不直接操作 HTML 元素,而是允许 HTML 元素反映我们状态中的值。

      import React, { useState } from "react"
      
      const MyComponent1 = () => {
        const [colorIndex, setColorIndex] = useState(0)
      
        const myColors = [
          "fuchsia",
          "cornflowerblue",
          "firebrick",
          "deepskyblue",
          "MediumAquamarine",
          "goldenrod",
          "OliveDrab",
          "darkmagenta",
          "orangered",
        ]
      
        const handleClick = () => {
          setColorIndex(colorIndex >= myColors.length - 1 ? 0 : colorIndex + 1)
        }
      
        return (
          <button style={{ color: myColors[colorIndex] }} onClick={handleClick}>
            Hello World
          </button>
        )
      }
      
      export { MyComponent }
      

      如果您还没有,现在可能是查看 React 文档的好时机,尤其是 Thinking in React

      【讨论】:

        猜你喜欢
        • 2016-11-26
        • 2011-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-30
        • 2021-06-13
        • 2019-08-20
        • 2013-12-29
        相关资源
        最近更新 更多