[React] React Fundamentals: Using Refs to Access Components

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 Components</title>
</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><label>{this.state.red}</label><br/>
                     <Silder update={this.myUpdate} ref="green"></Silder><label>{this.state.green}</label><br/>
                     <Silder update={this.myUpdate} ref="blue"></Silder><label>{this.state.blue}</label><br/>
                 </div>
            );
        }
    });

    var Silder = React.createClass({
        render: function(){
            return (
                 <input type="range" min="0" max="255"  onChange={this.props.update}/>
            )
        }
    });

    React.render(<React_app />, document.body);
</script>
</body>
</html>

 

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>  <!--  added  -->
                 <input type="range" min="0" max="255"  onChange={this.props.update}/>
               </div>  <!--  added  -->
            )
        }
    });

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
            });
        },

 

posted @ 2015-03-24 16:06  Zhentiw  阅读(491)  评论(0编辑  收藏  举报