Hi,
How can I reference a component my InputComponent give me a warning and it doesn’t work?
I added the ref to the component here
d: this.d.refs.input.value
in the render
<InputComponent
ref={ component => this.d = component }
onChange={() => this.updateMe()}
/>
{ this.state.d }
and the component:
class InputComponent extends React.Component {
render() {
return (
<div>
<input ref='input' type='text' onChange={this.props.updateMe} />
</div>
);
}
}
All the code
import React from 'react'
import ReactDOM from 'react-dom'
class UsingRefsToAccessComponents extends React.Component {
constructor(){
super()
this.state = {
a: '---'
}
}
updateMe = () => {
this.setState({
a: this.refs.a.value,
b: this.refs.b.value,
//reference 'c' with a node in the render(html)
c: this.c.value,
//refs to a component
//d: ReactDOM.findDOMNode(this.d).value// doesn't work with parent element in the component
d: this.d.refs.input.value
});
}
render() {
return (
<div>
<input
ref='a'
type='text'
onChange={() => this.updateMe()}
/>
{ this.state.a }
<hr />
<input
ref='b'
type='text'
onChange={() => this.updateMe()}
/>
{ this.state.b }
<hr />
<input
ref={ node => this.c = node }
type='text'
onChange={() => this.updateMe()}
/>
{ this.state.c }
<hr />
<InputComponent
ref={ component => this.d = component }
onChange={() => this.updateMe()}
/>
{ this.state.d }
</div>
);
}
}
class InputComponent extends React.Component {
render() {
return (
<div>
<input ref='input' type='text' onChange={this.props.updateMe} />
</div>
);
}
}
export default UsingRefsToAccessComponents