Se non può essere evitato il modello proposto estratto dal React docs sarebbe:
import React, {Component} from 'react';
const Child = ({setRef}) => <input type="text" ref={setRef} />;
class Parent extends Component {
constructor(props) {
super(props);
this.setRef = this.setRef.bind(this);
}
componentDidMount() {
// Call function on Child dom element
this.childInput.focus();
}
setRef(input) {
this.childInput = input;
}
render() {
return <Child setRef={this.setRef} />
}
}
Il Parentpassa una funzione come puntello vincolato al genitore s' this
. Reagire chiamerà il Bambino s' ref
callback setRef
e collegare la proprietà childInput
a this
che, come abbiamo già notato punti al genitore.
puoi pubblicare il tuo codice di reagire qui? this.props.children dovrebbe sempre essere una parola in questo caso ... – JordanHendrix
Per accedere al child possiamo aggiungere riferimento a e accedervi da thisre.reff.child. Questo non funzionerà sul componente connesso (un componente che è collegato a Redux o altri plugin). dobbiamo usare getWrappedInstance() per ottenere l'istanza avvolta e quindi possiamo accedere allo stato, ai riferimenti e ai metodi di quel componente. Ecco il video che lo spiega - https://youtu.be/VpdKjocgCtA –
Prem