Javascript 如何在 React 中访问 DOM 元素?React 中 document.getElementById() 的等价物是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38093760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access a DOM element in React? What is the equilvalent of document.getElementById() in React
提问by user504909
How do I select certain bars in react.js?
如何在 react.js 中选择某些栏?
This is my code:
这是我的代码:
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 (...);
}
I want to use this React component:
我想使用这个 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>
)
}
});
I want to execute the handleClick10 function and perform the operation for my selected progressbar. But the result I get is:
我想执行 handleClick10 函数并为我选择的进度条执行操作。但我得到的结果是:
You clicked: Progress1
TypeError: document.getElementById(...) is null
How do I select the certain Element in react.js?
如何在 react.js 中选择某个元素?
回答by Shubham Khatri
You can do that by specifying the ref
您可以通过指定 ref
EDIT:
编辑:
In React 16.3+, use React.createRef()
to create your ref:
在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} />;
}
}
In order to access the element, use:
要访问该元素,请使用:
const node = this.myRef.current;
DOC for using React.createRef()
EDIT
编辑
However facebook advises against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases.
然而 facebook 建议不要这样做,因为字符串引用有一些问题,被认为是遗留的,并且可能会在未来的版本之一中被删除。
From the docs:
从文档:
Legacy API: String Refs
If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.
旧 API:字符串引用
如果您之前使用过 React,您可能熟悉旧 API,其中 ref 属性是一个字符串,如“textInput”,并且 DOM 节点作为 this.refs.textInput 访问。我们建议不要这样做,因为字符串引用有一些问题,被认为是遗留的,并且可能会在未来的版本之一中被删除。如果您当前正在使用 this.refs.textInput 来访问 refs,我们建议您改用回调模式。
A recommended way for React 16.2 and earlieris to use the callback pattern:
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 }}/>
Even older versions of react defined refs using string like below
甚至旧版本的 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"/>
In order to get the element just do
为了得到元素就做
var object = this.refs.Progress1;
Remember to use this
inside an arrow function block like:
请记住this
在箭头功能块中使用,例如:
print = () => {
var object = this.refs.Progress1;
}
and so on...
等等...
回答by EQuimper
For getting the element in react
you need to use ref
and inside the function you can use the ReactDOM.findDOMNode
method.
为了获取元素,react
您需要使用ref
并且在函数内部您可以使用该ReactDOM.findDOMNode
方法。
But what I like to do more is to call the ref right inside the event
但我更喜欢做的是在事件内部调用 ref
<input type="text" ref={ref => this.myTextInput = ref} />
This is some good linkto help you figure out.
这是一些很好的链接,可以帮助您弄清楚。
回答by Piyush.kapoor
You can replace
你可以更换
document.getElementById(this.state.baction).addPrecent(10);
with
和
this.refs[this.state.baction].addPrecent(10);
<Progressbar completed={25} ref="Progress1" id="Progress1"/>
回答by Nikhil Kamani
Since React uses JSX code to create an HTML we cannot refer dom using regulation methods like documment.querySelector or getElementById.
由于 React 使用 JSX 代码来创建 HTML,因此我们不能使用诸如 documment.querySelector 或 getElementById 之类的规则方法来引用 dom。
Instead we can use React ref system to access and manipulate Dom as shown in below example:
相反,我们可以使用 React ref system 来访问和操作 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}
/>
);
}
}
}