[React Fundamentals] Using Refs to Access components

Source: Internet
Author: User

When your is using React components, you need to be able to access specific references to individual components. This is do by defining a ref .

Notice: ' Ref ' works in class component, not in statless component.

If we don ' t add "ref", three slider would mutate the same state, they won ' t has isolated scope.

If we want they behave differently, then we need to use it.

Import React from 'react'; import Reactdom from 'React-dom'; exportdefault classApp extends React.component {constructor () {super ();  This. State ={red:0, Green:0, Blue:0}} update () { This. SetState ({red:ReactDOM.findDOMNode ( This. Refs.red.refs.inp). Value, Green:ReactDOM.findDOMNode ( This. Refs.green.refs.inp). Value, Blue:ReactDOM.findDOMNode ( This. refs.blue.refs.inp).})} render () {return (            <div> <sliderref="Red"update={ This. Update.bind ( This)}></slider>                { This. state.red}ref="Green"update={ This. Update.bind ( This)}></slider>                { This. State.green}ref="Blue"update={ This. Update.bind ( This)}></slider>                { This. State.blue}        )    }}classSlider extends react.component{render () {//Refs would point to the input tag//If you wrap input inside div//Then you need to add another ref to the input//and access input like "THIS.REFS.RED.REFS.INP"        return (            <div> <input type="Range" ref="INP"min="0"Max="255"OnChange={ This. props.update}/> </div>        ); /*return (<input type= "range" min= "0" max= "255" OnC Hange={this.props.update}/>);*/    }}

[React Fundamentals] Using Refs to Access components

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.