[React] React Fundamentals: Using Refs to Access Components
程序员文章站
2022-04-13 13:42:40
...
When you are using React components you need to be able to access specific references to individual components. This is done by defining a ref . ! DOCTYPE html html head lang ="en" meta charset ="UTF-8" title React Lesson 5: Using Refs to
When you are using React components you need to be able to access specific references to individual components. This is done by defining a ref
.
DOCTYPE html>
html>
head lang="en">
meta charset="UTF-8">
title>React Lesson 5: Using Refs to Access Componentstitle>
head>
body>
script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.12.2/react.js">script>
script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.12.2/JSXTransformer.js">script>
script type="text/jsx">
var React_app = React.createClass({
getInitialState: function() {
return {
red: 128,
green: 128,
blue: 128
}
},
myUpdate: function(){
this.setState({
red: this.refs.red.getDOMNode().value,
green: this.refs.green.getDOMNode().value,
blue: this.refs.blue.getDOMNode().value
});
},
render: function() {
return (
div>
Silder update={this.myUpdate} ref="red">/Silder>
Here we use getDOMNode() to get the html node:
Silder update={this.myUpdate} ref="red">Silder>
then get value from it:
this.refs.red.getDOMNode().value
But, if we add a div:
var Silder = React.createClass({ render: function(){ return ( div> input type="range" min="0" max="255" onChange={this.props.update}/> div> ) } });
We found it doesn't work.
The way can solve this problem is by adding another ref to the input element:
var Silder = React.createClass({ render: function(){ return ( div > input type="range" min="0" max="255" ref="range" onChange={this.props.update}/> div> ) } });
myUpdate: function(){ this.setState({ red: this.refs.red.refs.range.getDOMNode().value, green: this.refs.green.refs.range.getDOMNode().value, blue: this.refs.blue.refs.range.getDOMNode().value }); },