如何在React中访问DOM元素?在React中document.getElementById()的等价物是什么?

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

本文关键字:React 是什么 getElementById 等价物 元素 访问 DOM document      更新时间:2023-09-26

如何在react.js中选择某些栏?

这是我的代码:

var Progressbar = React.createClass({
    getInitialState: function () {
        return { completed: this.props.completed };
    },
    addPrecent: function (value) {
        this.props.completed += value;
        this.setState({ completed: this.props.completed });
    },
    render: function () {
        var completed = this.props.completed;
        if (completed < 0) { completed = 0 };

        return (...);
    }

我想使用这个React组件:

var App = React.createClass({
    getInitialState: function () {
        return { baction: 'Progress1' };
    },
    handleChange: function (e) {
        var value = e.target.value;
        console.log(value);
        this.setState({ baction: value });
    },
    handleClick10: function (e) {
        console.log('You clicked: ', this.state.baction);
        document.getElementById(this.state.baction).addPrecent(10);
    },
    render: function () {
        return (
            <div class="center">Progress Bars Demo
            <Progressbar completed={25} id="Progress1" />
                <h2 class="center"></h2>
                <Progressbar completed={50} id="Progress2" />
                <h2 class="center"></h2>
                <Progressbar completed={75} id="Progress3" />
                <h2 class="center"></h2>
                <span>
                    <select name='selectbar' id='selectbar' value={this.state.baction} onChange={this.handleChange}>
                        <option value="Progress1">#Progress1</option>
                        <option value="Progress2">#Progress2</option>
                        <option value="Progress3">#Progress3</option>
                    </select>
                    <input type="button" onClick={this.handleClick10} value="+10" />
                    <button>+25</button>
                    <button>-10</button>
                    <button>-25</button>
                </span>
            </div>
        )
    }
});

我想要执行handleClick10函数并对我选择的进度条执行操作。但是我得到的结果是

 You clicked:  Progress1
 TypeError: document.getElementById(...) is null

如何在react.js中选择特定的元素?

您可以通过指定ref

EDIT:在带有函数组件的react v16.8.0中,你可以用useRef定义一个ref。注意,当你在函数组件上指定ref时,你需要使用React。使用useImperativeHandle来从函数组件中公开某些函数

,

const Child1 = React.forwardRef((props, ref) => {
    return <div ref={ref}>Child1</div> 
});
const Child2 = React.forwardRef((props, ref) => {
    const handleClick= () =>{};
    useImperativeHandle(ref,() => ({
       handleClick
    }))
    return <div>Child2</div> 
});
const App = () => {
    const child1 = useRef(null);
    const child2 = useRef(null);
    return (
        <>
           <Child1 ref={child1} />
           <Child1 ref={child1} />
        </>
    )
}
编辑:

React 16.3+中,使用React.createRef()创建ref:
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

要访问该元素,使用:

const node = this.myRef.current;

使用React.createRef()的DOC


编辑

但是facebook不建议这样做,因为字符串refs有一些问题,被认为是遗留的,并且很可能在未来的一个版本中被删除。

From the docs:

Legacy API: String Refs

如果你以前使用过React,你可能会熟悉旧的API,其中ref属性是字符串,如"textInput", DOM节点作为this.ref . textinput访问。我们建议反对它,因为字符串refs有一些问题,被考虑遗留的,并且很可能在将来的某个版本中被删除。如果你目前正在使用this.ref . textinput来访问ref建议使用回调模式。

React 16.2和更早版本的推荐方法是使用回调模式:
<Progressbar completed={25} id="Progress1" ref={(input) => {this.Progress[0] = input }}/>
<h2 class="center"></h2>
<Progressbar completed={50} id="Progress2" ref={(input) => {this.Progress[1] = input }}/>
  <h2 class="center"></h2>
<Progressbar completed={75} id="Progress3" ref={(input) => {this.Progress[2] = input }}/>

使用回调的DOC


甚至旧版本的react定义refs使用像下面这样的字符串

<Progressbar completed={25} id="Progress1" ref="Progress1"/>
    <h2 class="center"></h2>
    <Progressbar completed={50} id="Progress2" ref="Progress2"/>
      <h2 class="center"></h2>
    <Progressbar completed={75} id="Progress3" ref="Progress3"/>

要获取元素,只需执行

var object = this.refs.Progress1;

请记住在箭头函数块中使用this,如:

print = () => {
  var object = this.refs.Progress1;  
}

等等…

要获取react中的元素,您需要使用ref,而在函数内部,您可以使用ReactDOM.findDOMNode方法。

但是我更喜欢在事件

中调用ref
<input type="text" ref={ref => this.myTextInput = ref} />

这是一个很好的链接,可以帮助你弄清楚。

在新版本的React中,你可以像这样通过钩子来使用和操作DOM:

import React, { useEffect, useRef } from "react";
const MyComponent = () => {
  const myContainer = useRef(null);
  
  useEffect(() => {
    console.log("myContainer..", myContainer.current);
  });
  return (
    <>
      <h1>Ref with react</h1>
      <div ref={myContainer}>I can use the DOM with react ref</div>
    </>
  );
};
export default MyComponent;

当你想访问你的DOM元素只需使用myContainer.current

你可以替换

document.getElementById(this.state.baction).addPrecent(10);

this.refs[this.state.baction].addPrecent(10);

  <Progressbar completed={25} ref="Progress1" id="Progress1"/>

免责声明:虽然上面的答案可能是一个更好的解决方案,但作为一个初学者,当你想要的只是一些非常简单的东西时,它会让你难以接受。这是为了更直接地回答你原来的问题"我如何在react中选择某些元素"

我认为你的问题中的混乱是因为你有React 组件s,你正在传递id "Progress1", "Progress2"等。我相信这不是在设置html属性'id',而是在设置React组件属性。例如

class ProgressBar extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            id: this.props.id    <--- ID set from <ProgressBar id="Progress1"/>
        }
    }        
}

正如上面提到的一些答案,你完全可以在React应用程序中使用document.querySelector,但你必须清楚,它是选择组件的渲染方法的html输出。所以假设你的渲染输出看起来像这样:

render () {
    const id = this.state.id
    return (<div id={"progress-bar-" + id}></div>)
}

然后你可以在其他地方做一个普通的javascript querySelector调用,像这样:

let element = document.querySelector('#progress-bar-Progress1')

在类和功能组件中必须遵循两种不同的方法。

  1. 对于类组件

    <input type="text" ref={ref => this.myTextInput = ref} />
    

看看上面的代码。使用"ref"属性来引用相关元素。然后,您将能够使用该引用来引用该元素。在这个例子中,我可以使用"this. mytextinput& quot;引用上述输入元素。

  • 功能组件

    const textInput = useRef(null)
    
  • 使用" userf "钩子,并将该变量名设置为"ref"要引用的元素的属性(如下所示)。

    <input type="text" ref={textInput} />
    

    一个关于功能组件的例子。

    import React, {useRef} from 'react'
    function CustomTextInput(props) {
      // textInput must be declared here so the ref can refer to it
      const textInput = useRef(null);
      function handleClick() {
         textInput.current.focus();
      }
      return (
        <div>
         <input type="text" ref={textInput} />
        </div>
      );
    }
    

    想了解更多?

    由于React使用JSX代码来创建HTML,我们不能使用像document这样的调节方法来引用dom。querySelector or getElementById.

    相反,我们可以使用React ref系统来访问和操作Dom,如下面的例子所示:

    constructor(props){
        super(props);
        this.imageRef = React.createRef(); // create react ref
    }
    componentDidMount(){
        **console.log(this.imageRef)** // acessing the attributes of img tag when dom loads
    }
    
    render = (props) => {
    const {urls,description} = this.props.image;
        return (
                <img
                 **ref = {this.imageRef} // assign the ref of img tag here**
                 src = {urls.regular} 
                 alt = {description}
                 />
            );
    }
    

    }

    在我的情况下,我不能使用ref,因为元素是在许多子组件之间的某个地方,我必须通过类和id而不是ref来访问它们。所以,尝试使用useEffect钩子不起作用,因为它找不到元素:

    useEffect(() => {
      const el1 = document.querySelector('.el1')
      const el2 = document.querySelector('.el2')
    }, [])
    

    元素是undefined,因为当它被挂载时,子组件也不会在父组件之前挂载。

    那么,我所做的就是使用timeout:

    useEffect(() => {
      const timer = setTimeout(() => {
        const el1 = document.querySelector('.el1')
        const el2 = document.querySelector('.el2')
      },500)
      return () => {
        clearTimeout(timer)
      }
    }, [])
    

    现在,它工作正常。它找到了DOM,我可以对它们进行操作。希望这能帮助到一些人!

    在React中相当于document.getElementById()的是document.querySelector()