2016-06-29 14 views
33

Come seleziono determinate barre in react.js?Come accedere a un elemento DOM in React? Qual è l'equivalente di document.getElementById() in React

Questo è il mio codice:

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 (...); 
} 

voglio usare questo componente 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> 
) 
} 

}); 

voglio eseguire la funzione handleClick10 ed eseguire l'operazione per il mio progressbar selezionato. Ma il risultato che ottengo è:

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

Come si seleziona l'elemento certo in react.js?

risposta

40

Potete farlo specificando il ref

<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"/> 

Al fine di ottenere l'elemento basta fare

var object = this.refs.Progress1; 

e così via ...

EDIT

Tuttavia facebook consiglia contro i t perché i riferimenti alle stringhe hanno alcuni problemi, sono considerati legacy e probabilmente verranno rimossi in una delle versioni future.

Dalla documentazione:

Legacy API: String Refs

Se hai lavorato con Reagire prima, si potrebbe essere familiarità con un'API più vecchio in cui l'attributo ref è una stringa, come "textInput", e al nodo DOM si accede come this.refs.textInput. Noi ci sconsigliamo perché i riferimenti alle stringhe hanno alcuni problemi, sono considerati legacy e probabilmente verranno rimossi in una delle versioni future. Se stai attualmente utilizzando this.refs.textInput per accedere a refs, noi consigliamo invece il pattern di callback.

Un modo consigliato è quello di utilizzare il modello di callback

Spero che aiuta

<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 for using callback

+1

Facebook sconsiglia questo approccio. Vedi qui https://facebook.github.io/react/docs/refs-and-the-dom.html – Dmitry

+0

@dmitrymar Come posso vedere la pagina sopra è scritta per la v15.4.2 in poi e immagino, questo non era lì prima quando ho scritto la risposta. In ogni caso ha modificato la risposta con l'approccio corretto –

10

Per ottenere l'elemento in reagire è necessario utilizzare ref e dentro la funzione è possibile utilizzare il metodo ReactDOM.findDOMNode.

Ma quello che mi piace fare di più E 'per chiamare l'arbitro proprio all'interno della manifestazione

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

Questo è un buon collegamento per aiutarvi capito.

https://facebook.github.io/react/docs/refs-and-the-dom.html

+1

Questo è il modo corretto per farlo. Questo aggiunge un riferimento all'elemento sull'oggetto/classe a cui puoi semplicemente usare 'this.myTextInput' per accedere. –

3

È possibile sostituire

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

da

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


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